<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\message\MessageNotifyController;
use app\controller\wmapi\PublicCommentController;
use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaMembers;
use app\model\WaMonthlySettlement;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\controller\wmapi\IndexController;
use app\model\WaOrdersPurchaseContract;
use app\model\WaOrdersPurchaseOperateLog;
use app\model\WaOrdersRelevance;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaProducts;
use app\model\WaOrdersPurchaseAmountDetail;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaPurchaseOrdersExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaRegistrationCompany;
use app\model\WaSupplier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;

//use Illuminate\Database\Capsule\Manager;
use support\exception\Handler;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;

class OrderPurchaseController extends Validate
{

    /**
     * 创建采购订单 - 手动
     * @param Request $request
     * @return Response
     * 订单创建人->下单用户->下了几款车型笔->多少量->从哪里发到哪里->中间产生了多少费用
     */
    public function createPurchaseOrder(Request $request)
    {
//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        \support\Db::beginTransaction();
        try {
            /**
             * 创建采购订单编号
             */
            $purchase_order_sn = 'WMHTC' . IndexController::generateOrderSnOther();
            $order_data['purchase_order_sn'] = $purchase_order_sn;

            // 供应商信息
            $supplier = WaSupplier::find(['id' => $param['supplier_id']]);
            $supplier = json_decode($supplier);
            if (!$supplier) {
                return IndexController::errored('', '供应商信息获取失败，无法创建采购单');
            }

            // 采购订单数据的-入参参数
            $order_data_add = OrderPurchaseController::dataByCreate($param, $supplier, $adminId, $purchase_order_sn, $order_data);
            if ($order_data_add != true) {
                return IndexController::errored('', $order_data_add);
            }
            // 车型信息 + (订单采购主订单 + 子订单 创建)
            $specs_created = OrderPurchaseController::specsByCreate($param, $order_data, $purchase_order_sn, $order_detail_id);
            if ($specs_created != true) {
                return IndexController::errored('', $specs_created);
            }
            // 添加采购订单账单明细
            $bill_details_add = OrderPurchaseController::billDetailsByCreate($param, $purchase_order_sn, $adminId, $supplier, $bill_details_id);
            if ($bill_details_add != true) {
                return IndexController::errored('', $bill_details_add);
            }
            if ($order_data && $order_detail_id && $bill_details_id) {
                \support\Db::commit();
                return IndexController::successed('', '采购单创建成功');
            } else {
                return IndexController::errored($order_data . '+++++' . $order_detail_id . '+++++' . $bill_details_id, '创建采购订单失败');
            }

        } catch (\Throwable $exception) {
            IndexController::logError('createPurchaseOrder', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '创建采购订单失败');
        }
    }

    public static function dataByCreate($param, $supplier, $adminId, $purchase_order_sn, &$order_data)
    {
        if ($param['registration_company_id']) {
            $registration_condition = [];
            $registration_condition [] = ['id', '=', $param['registration_company_id']];
            $regist_rationCompany = WaRegistrationCompany::find($registration_condition);
            if (!$regist_rationCompany) {
                return '上牌公司信息为空';
            }
        } else {
            return '上牌公司id为必填';
        }

        $order_data = [
            // 采购单产品字段 公共字段
            'purchase_orders_status' => 0, // 采购单状态 0 草稿 1审批中 2待签署审批合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
            'created_at' => dateTime(), // 创建时间
            'supplier_id' => $param['supplier_id'], // 供应商id
            'supplier_name' => $supplier->name, // 供应商名字
            'supplier_credit_code' => $supplier->credit_code, // 组织机构信用代码
            'supplier_linkman' => $supplier->linkman, // 联系人
            'supplier_phone' => $supplier->phone, // 联系电话
            'supplier_email' => $supplier->email, // 邮箱
            'supplier_province' => $supplier->province, // 省份
            'supplier_city' => $supplier->city, // 市
            'supplier_main_brand' => $supplier->main_brand, // 供应商主营品牌
            'supplier_type' => 1, // 供应商类型
            'purchase_order_sn' => $purchase_order_sn, //
            'admin_id' => $adminId->id, // 创建人id
            'admin_name' => $adminId->nickname, // 创建人名称
            'contract_price' => $param['contract_price'], // 合同金额


            'delivery_province' => $param['delivery_province'], // 交付地点-省
            'delivery_city' => $param['delivery_city'], // 交付地点-市
            'deposit_price' => $param['deposit_price'], // 定金金额
            'deposit_ratio' => $param['deposit_ratio'], // 定金比例
            'supplementary_terms' => $param['supplementary_terms'], // 补充条款
//            'delivery_accessories' => $param['delivery_accessories'], // 交车附件

            'registration_company_id' => $param['registration_company_id'], // 上牌公司id
            'registration_company_name' => $param['registration_company_name'], // 上牌公司名字
            'is_mine_registration_company' => $param['is_mine_registration_company'], // 是否自己的牌照挂靠公司 1 是 2 不是
//            'transfer_export_company_id' => $param['transfer_export_company_id'], // 出口公司id
//            'transfer_export_company_name' => $param['transfer_export_company_name'], // 出口公司名字

            'registration_company_province' => $param['registration_company_province'], //挂牌公司-省份
            'registration_company_city' => $param['registration_company_city'], //挂牌公司-市
//            'transfer_export_company_province' => $param['transfer_export_company_province'], //出口公司-省份
//            'transfer_export_company_city' => $param['transfer_export_company_city'], //出口公司-市

            'registration_credit_code' => $param['registration_credit_code'], //挂靠公司-组织机构信用代码
//            'transfer_export_credit_code' => $param['transfer_export_credit_code'], //出口公司-组织机构信用代码


        ];

        if (array_key_exists('registration_company_info', $param)) {
            if ($param['registration_company_info']){
                $order_data['registration_company_info'] = json_encode($param['registration_company_info']);
            }
        }
        if (array_key_exists('latest_delivery_time', $param)) {
            if ($param['latest_delivery_time']) {
                $order_data['latest_delivery_time'] = $param['latest_delivery_time'];// 最晚交付时间
            }
        }
        if (array_key_exists('remark', $param)) {
            if ($param['remark']) {
                $order_data['remark'] = $param['remark'];// 最晚交付时间
            }
        }

        return 'true';
    }

    public static function childrenDetailDataByCreate($param, $key, $purchase_order_sn, $order_sn_child, &$order_detail_data)
    {

        $deposit_total_price = $key['deposit_total_price'];

        $order_detail_data = [
            'guide_price' => $key['guide_price'], // 指导价
            'purchase_order_sn_parent' => $purchase_order_sn, // 采购单父订单编号
            'purchase_order_sn_child' => $order_sn_child, // 子订单编号
            'brands_name' => $key['brands_name'], // 品牌
            'series_name' => $key['series_name'], // 车系
            'model' => $key['model'], // 车型名称
            'retail_concessions' => $key['retail_concessions'], // 零点优惠
            'purchase_quotation' => $key['purchase_quotation'], // 车辆采购价格/采购报价
            'count' => $key['count'], // 数量
            'supplier_id' => $param['supplier_id'], // 供应商id
            'created_at' => dateTime(), // 创建时间


            'other_concessions' => '', // 其它优惠
            'vehicle_status' => $key['vehicle_status'], // 车辆状况(是否是新车)  1 新车 2 二手车
            'sub_brand_name' => $key['sub_brand_name'], // 厂商
            'market_time' => $key['market_time'], // 上市日期
            'is_nev' => $key['is_nev'], // 是否是新能源
            'seat_count' => $key['seat_count'], // 车座数
            'purchase_price' => $key['purchase_price'], // 二手车采购价格
            'VAT_invoice_price' => $key['VAT_invoice_price'], // 增值税发票金额
            'other_rebates' => $key['other_rebates'], // 采购返利
//            'registration_province' => $key['registration_province'], // 上牌省份
//            'registration_city' => $key['registration_city'], // 上牌市区
//            'registration_id' => $key['registration_id'], // 上牌服务商id
//
//            'transfer_export_province' => $key['transfer_export_province'], // 转移待出口省份
//            'transfer_export_city' => $key['transfer_export_city'], // 转移待出口市区
//            'transfer_export_id' => $key['transfer_export_id'], // 转移待出口服务商id

            'purchase_single_quotation' => $key['purchase_single_quotation'], // 采购单价

            'car_year' => $key['car_year'], //  车辆年款
            'jb' => $key['jb'], // 级别
            'series_type' => $key['series_type'], // 车身类型
            'driver_form' => $key['driver_form'], // 驱动方式
            'length' => $key['length'], // 长
            'width' => $key['width'], // 宽
            'height' => $key['height'], // 高
            'curb_weight' => $key['curb_weight'], // 设计重量


            'deposit_single_price' => $deposit_total_price / $key['count'], // 定金单价金额
            'deposit_total_price' => $deposit_total_price, // 定金总价金额
            'purchase_single_quotation' => $key['purchase_single_quotation'], // 车辆采购单价金额
            'purchase_total_price' => $key['purchase_total_price'], // 车辆采购总价金额(原来是 total_price 字段现在修改成此字段 )
            'resource_service_fee' => $key['resource_service_fee'], // 资源服务费
            'is_drawback' => $key['is_drawback'], // 是否退税
            'is_CLIVTA' => $key['is_CLIVTA'], // 是否交强险  文森说的 要大些
        ];
        if ($key['other_price']){
            $order_detail_data['other_price'] = json_encode($key['other_price']);// 其它费用
        }

        if ($key['option_package']){
            $order_detail_data['option_package'] = json_encode($key['option_package']);// 选装包
        }

        if ($key['price_options']){
            $order_detail_data['price_options'] = json_encode($key['price_options']);// 费用选项
        }
//        if (array_key_exists('invoice_price',$key)){
//            if ($key['invoice_price']){
//                $order_detail_data['invoice_price'] = $key['invoice_price']; // 机动车专用发票价
//            }
//        }

        if (array_key_exists('color_interior', $key)) {
            $order_detail_data['color_interior'] = $key['color_interior']; // 内饰颜色
        }
        if (array_key_exists('color_exterior', $key)) {
            $order_detail_data['color_exterior'] = $key['color_exterior']; // 外观颜色
        }
        return 'true';
    }

    public static function monthlySettlementByCreate($param, $kd, $supplier, $purchase_order_sn, $adminId)
    {
        if ($kd['price_name'] == '检测报告费') {
            $type = 999;
        } elseif ($kd['price_name'] == '国内物流费') {
            $type = 999;
        } elseif ($kd['price_name'] == '国际快递费') {
            $type = 999;
        } elseif ($kd['price_name'] == '上牌费') {
            $type = 999;
        } elseif ($kd['price_name'] == '购置税') {
            $type = 999;
        }
        $data_monthly_settlement = [
            'type' => $type,
            'supplier_id' => $param['supplier_id'],
            'supplier_name' => $supplier->name,
            'price_name' => $kd['price_name'], // 款项类目名称(购置税，上牌费用等)
            'purchase_order_sn' => $purchase_order_sn,
            'created_at' => dateTime(),
//            'settlement_sratus' => 1, // 结算状态 1 待结算 2 请款中 3 已结算 4 删除
            'approve_stauts' => 0, // 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
            'payroll_approve_sn' => $purchase_order_sn,
            'admin_id' => $adminId->id,
            'admin_name' => $adminId->nickname,
            'total_amount' => $kd['total_amount'],
            'module_type' => 1, // 模块类型 1 采购模块 2 车辆管理模块
        ];
        $res = WaMonthlySettlement::created($data_monthly_settlement);
        if (!$res) {
            return '创建月结款项数据失败';
        }
        return 'ture';
    }

    public static function billDetailsByCreate($param, $purchase_order_sn, $adminId, $supplier, &$bill_details_id)
    {
        $bill_details = $param['bill_details'];
        if ($bill_details) {
            foreach ($bill_details as $kd) {
                $bill_details_data = [
                    'purchase_order_sn' => $purchase_order_sn, //
                    'total_amount' => $kd['total_amount'], //
                    'price_name' => $kd['price_name'], //
                    'admin_id' => $adminId->id, //
                    'admin_name' => $adminId->nickname, //
                    'created_at' => dateTime(), //
                ];
                $monthly_sellement = ['检测报告费', '国内物流费', '国际快递费'];

                if ($kd['price_name'] && in_array($kd['price_name'], $monthly_sellement)) {
                    $bill_details_data['is_monthly_settlement'] = 2;
                    // 创建月结款项列表
                    $settlement_add = OrderPurchaseController::monthlySettlementByCreate($param, $kd, $supplier, $purchase_order_sn, $adminId);
                    if ($settlement_add != 'true') {
                        return IndexController::errored('', $settlement_add);
                    }
                }

                $bill_details_id = WaOrdersPurchaseAmountDetail::created($bill_details_data); // 创建订单详情
                if (!$bill_details_id) {
                    return '添加采购订单账单明细失败';
                }
            }
        } else {
            return '采购费用，参数值为空';
        }
        return 'true';
    }

    public static function specsByCreate($param, $order_data, $purchase_order_sn, &$order_detail_id)
    {
        $specs = $param['specs_can'];//车型信息

        if ($specs) {
            // 主采购单字段
            $orders_purchase_id = WaOrdersPurchase::created($order_data); // 创建采购单
            if (!$orders_purchase_id) {
                return IndexController::errored('', '创建采购单失败');
            }
            foreach ($specs as $key) {
                $order_sn_child = 'WMCDZ' . IndexController::generateOrderSnOther(); // 子订单编号
                //采购订单子订单入参数据
                $order_detail_data_check = OrderPurchaseController::childrenDetailDataByCreate($param, $key, $purchase_order_sn, $order_sn_child, $order_detail_data);
                if ($order_detail_data_check != 'true') {
                    return IndexController::errored('', '日志添加失败失败');
                }

                if (array_key_exists('order_sn_child', $key)) {
                    $condtion_order = [];
                    $condtion_order [] = ['order_sn_child', '=', $key['order_sn_child']];
                    $condtion_order_data = WaOrdersRelevance::find($condtion_order);
                    $condtion_order_data = json_decode($condtion_order_data);
                    if ($condtion_order_data) {
                        $order_detail_data['order_sn_child'] = $condtion_order_data->order_sn_child;
                        $order_detail_data['order_sn_parent'] = $condtion_order_data->order_sn_parent;
                    }
                }
                $order_detail_id = WaOrdersPurchaseRelevance::created($order_detail_data); // 创建订单详情
                if (!$order_detail_id) {
                    return IndexController::error_by_static($order_detail_id, '创建报价单失败');
                }

                // 更新采购订单的定金总额
                $purchase_amount_condition = [];
                $purchase_amount_condition [] = ['purchase_order_sn_parent', '=', $purchase_order_sn];
                $deposit_price = WaOrdersPurchaseRelevance::sumByDeposit($purchase_amount_condition); // 定金总价金额
                $total_amount = WaOrdersPurchaseRelevance::sumByPurchaseTotalPrice($purchase_amount_condition); // 采购车辆总价
                $balance_total_price = round($total_amount, 2) - round($deposit_price, 2);  // 采购订单尾款
                $purchase_order_up_condition = [];
                $purchase_order_up_condition [] = ['purchase_order_sn', '=', $purchase_order_sn];
                $condtion_order_purchase_data = [
                    'deposit_price' => round($deposit_price, 2),
                    'total_amount' => round($total_amount, 2),
                    'balance_total_price' => round($balance_total_price, 2),
                    'updated_at' => dateTime(),
                ];
                $condtion_order_purchase_up = WaOrdersPurchase::updated($condtion_order_purchase_data, $purchase_order_up_condition);
                if (!$condtion_order_purchase_up) {
                    return IndexController::error_by_static($order_detail_id, '创建采购订单定金价格更新失败');
                }

                if (array_key_exists('order_sn_child', $key)) {
                    $where_dec = [];
                    $where_dec [] = ['order_sn_child', '=', $key['order_sn_child']];
                    $where_dec [] = ['model', '=', $key['model']];
                    $decrement = WaOrdersRelevance::decrement($where_dec, $key['count']);
                    if (!$decrement) {
                        return IndexController::error_by_static($order_detail_id, '订单详情的产品数量递减失败');
                    }
                }
            }

        } else {
            return IndexController::error_by_static($specs, '创建采购单失败，参数值为空');
        }
        return $order_detail_id;
    }


    /**
     * 更新采购订单
     * @param Request $request
     * @return Response
     */
    public function updatePurchaseOrder(Request $request)
    {

//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取采购订单编号
        if (!$param['purchase_order_sn']) {
            return IndexController::errored('1', '订单编号不能为空');
        }
        \support\Db::beginTransaction();
        try {


//        $purchase_order_sn = 'WMHTC'.IndexController::generateOrderSn(); // 采购订单编号
//        $order_data['purchase_order_sn'] = $purchase_order_sn; // 采购订单编号
            // 供应商信息
            $supplier = WaSupplier::find(['id' => $param['supplier_id']]);
            $supplier = json_decode($supplier);
            if (!$supplier) {
                return IndexController::errored('2', '供应商信息获取失败，无法创建采购单');
            }

            // 创建采购订单数据的-入参参数
            $order_data_up = OrderPurchaseController::dataByUpdate($param, $supplier, $adminId, $order_data);
            if ($order_data_up != 'true') {
                return IndexController::errored('3', $order_data_up);
            }
            //车型信息 + (订单采购主订单 + 子订单 更新)
            $specs_up = OrderPurchaseController::specsByUpdate($param, $order_data, $param['purchase_order_sn'], $specs, $order_detail_id);
            if ($specs_up != 'true') {
                return IndexController::errored('4', $specs_up);
            }
            // 删除账单明细旧数据
            $where_bill_details = [];
            $where_bill_details [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $bill_del = WaOrdersPurchaseAmountDetail::deleted($where_bill_details);
            //删除该笔采购订单的月结账单
            $where_monthly_settlement = [];
            $where_monthly_settlement [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $monthly_del = WaMonthlySettlement::deleted($where_monthly_settlement);
            /**
             * 添加采购订单账单明细
             */
            $bill_details_up = OrderPurchaseController::billDetailsByUpdate($param, $param['purchase_order_sn'], $adminId, $supplier, $bill_details_id);
            if ($bill_details_up != 'true') {
                return IndexController::errored('5', $bill_details_up);
            }
            \support\Db::commit();
            return IndexController::successed('', '采购单更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('updatePurchaseOrder', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored('', '采购单更新失败');

        }
    }

    public static function dataByUpdate($param, $supplier, $adminId, &$order_data)
    {
        $registration_company_id = ''; // 非我司没有id
        if (array_key_exists('registration_company_id',$param)){
            if ($param['registration_company_id']) {
                $registration_condition = [];
                $registration_condition [] = ['id', '=', $param['registration_company_id']];
                $regist_rationCompany = WaRegistrationCompany::find($registration_condition);
                $registration_company_id = $param['registration_company_id'];
            }
        }


        $order_data = [
            // 采购单产品字段 公共字段
            'purchase_orders_status' => 0, // 采购单状态 0 草稿 1审批中 2待签署审批合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
            'supplier_id' => $param['supplier_id'], // 供应商id
            'supplier_name' => $supplier->name, // 供应商名字
            'supplier_credit_code' => $supplier->credit_code, // 组织机构信用代码
            'supplier_linkman' => $supplier->linkman, // 联系人
            'supplier_phone' => $supplier->phone, // 联系电话
            'supplier_email' => $supplier->email, // 邮箱
            'supplier_province' => $supplier->province, // 省份
            'supplier_city' => $supplier->city, // 市
            'supplier_main_brand' => $supplier->main_brand, // 市
            'admin_id' => $adminId->id, // 创建人id
            'admin_name' => $adminId->nickname, // 创建人名称


            'delivery_province' => $param['delivery_province'], // 交付地点-省
            'delivery_city' => $param['delivery_city'], // 交付地点-市
            'contract_price' => $param['contract_price'], // 合同金额
            'deposit_price' => $param['deposit_price'], // 定金金额
            'deposit_ratio' => $param['deposit_ratio'], // 定金比例
            'supplementary_terms' => $param['supplementary_terms'], // 补充条款
//            'delivery_accessories' => $param['delivery_accessories'], // 交车附件
            'updated_at' => dateTime(), // 更新订单


            'registration_company_id' => $registration_company_id, // 上牌公司id
            'registration_company_name' => $param['registration_company_name'], // 上牌公司名字
            'is_mine_registration_company' => $param['is_mine_registration_company'], // 是否自己的牌照挂靠公司 1 是 2 不是
//            'transfer_export_company_id' => $param['transfer_export_company_id'], // 出口公司id
//            'transfer_export_company_name' => $param['transfer_export_company_name'], // 出口公司名字

            'registration_company_province' => $param['registration_company_province'], //挂牌公司-省份
            'registration_company_city' => $param['registration_company_city'], //挂牌公司-市
//            'transfer_export_company_province' => $param['transfer_export_company_province'], //出口公司-省份
//            'transfer_export_company_city' => $param['transfer_export_company_city'], //出口公司-市
            'registration_credit_code' => $param['registration_credit_code'], //挂靠公司-组织机构信用代码
//            'transfer_export_credit_code' => $param['transfer_export_credit_code'], //出口公司-组织机构信用代码

        ];


        if (array_key_exists('registration_company_info', $param)) {
            $order_data['registration_company_info'] = json_encode($param['registration_company_info']);
        }

        if (array_key_exists('transfer_export_company_info', $param)) {
            $order_data['transfer_export_company_info'] = json_encode($param['transfer_export_company_info']);
        }


        if (array_key_exists('latest_delivery_time', $param)) {
            if ($param['latest_delivery_time']) {
                $order_data['latest_delivery_time'] = $param['latest_delivery_time'];// 最晚交付时间

            }
        }

        if (array_key_exists('remark', $param)) {
            if ($param['remark']) {
                $order_data['remark'] = $param['remark'];// 最晚交付时间
            }
        }

        return 'true';
    }

    public static function childrenDetailDataByUpdate($param, $key, $purchase_order_sn, $order_sn_child, &$order_detail_data)
    {
        $deposit_total_price = 0;
        if (array_key_exists('deposit_single_price', $key)) {

            if ($key['deposit_single_price'] && $key['deposit_single_price'] != 0) {
                $deposit_total_price = $key['deposit_single_price'] * $key['count'];
            }
        }

        $order_detail_data = [
            'guide_price' => $key['guide_price'], // 指导价
            'purchase_order_sn_parent' => $purchase_order_sn, // 采购单父订单编号
            'purchase_order_sn_child' => $order_sn_child, // 子订单编号
//            'product_type' => $key['product_type'], // 产品类型
//            'car_type' => $key['car_type'], // 汽车类型 car_type 1轿车 2 SUV 3 MPV 4 跑车 5新能源
            'brands_name' => $key['brands_name'], // 品牌
            'series_name' => $key['series_name'], // 车系
            'model' => $key['model'], // 车型名称
            'retail_concessions' => $key['retail_concessions'], // 零点优惠
            'purchase_quotation' => $key['purchase_quotation'], // 车辆采购价格/采购报价
            'count' => $key['count'], // 数量
//            'total_price' => $key['total_price'], // 总价
            'supplier_id' => $param['supplier_id'], // 供应商id
            'created_at' => dateTime(), // 创建时间
            'other_price' => json_encode($key['other_price']), // 其它费用

            'vehicle_status' => $key['vehicle_status'], // 车辆状况(是否是新车)  1 新车 2 二手车




            'transfer_export_province' => $key['transfer_export_province'], // 转移待出口省份
            'transfer_export_city' => $key['transfer_export_city'], // 转移待出口市区
            'transfer_export_id' => $key['transfer_export_id'], // 转移待出口服务商id
            'option_package' => json_encode($key['option_package']), // 选装包
            'price_options' => json_encode($key['price_options']), // 费用选项
            'sub_brand_name' => $key['sub_brand_name'], // 厂商
            'deposit_total_price' => $deposit_total_price, // 定金总价金额
            'car_year' => $key['car_year'], //  车辆年款
            'purchase_price' => $key['purchase_price'], // 二手车采购价格
            'purchase_single_quotation' => $key['purchase_single_quotation'], // 车辆采购单价金额
            'other_rebates' => $key['other_rebates'], // 采购返利
            'purchase_total_price' => $key['purchase_total_price'], // 车辆采购总价金额(原来是 total_price 字段现在修改成此字段 )
            'resource_service_fee' => $key['resource_service_fee'], // 资源服务费
            'is_drawback' => $key['is_drawback'], // 是否退税
            'is_CLIVTA' => $key['is_CLIVTA'], // 是否交强险  文森说的 要大些
            'is_nev' => $key['is_nev'], // 是否是新能源
            'deposit_single_price' => $key['deposit_single_price'], // 定金单价金额

        ];

        if (array_key_exists('color_interior', $key)) {
            $order_detail_data['color_interior'] = $key['color_interior']; // 内饰颜色
        }
        if (array_key_exists('color_exterior', $key)) {
            $order_detail_data['color_exterior'] = $key['color_exterior']; // 外观颜色
        }
        if (array_key_exists('order_sn_child', $key)) {
            $order_detail_data['order_sn_child'] = $key['order_sn_child']; // 外观颜色
        }
        if (array_key_exists('order_sn_parent', $key)) {
            $order_detail_data['order_sn_parent'] = $key['order_sn_parent']; // 外观颜色
        }

//        if (array_key_exists('invoice_price',$key)){
//            if ($key['invoice_price']){
//                $order_detail_data['invoice_price'] = $key['invoice_price']; // 机动车专用发票价
//            }
//        }

        return 'true';
    }

    public static function monthlySettlementByUpdate($param, $kd, $supplier, $purchase_order_sn, $adminId)
    {

        if ($kd['price_name'] == '检测报告费') {
            $type = 999;
        } elseif ($kd['price_name'] == '国内物流费') {
            $type = 999;
        } elseif ($kd['price_name'] == '国际快递费') {
            $type = 999;
        } elseif ($kd['price_name'] == '上牌费') {
            $type = 999;
        } elseif ($kd['price_name'] == '购置税') {
            $type = 999;
        }
        $data_monthly_settlement = [
            'type' => $type,
            'supplier_id' => $param['supplier_id'],
            'supplier_name' => $supplier->name,
            'price_name' => $kd['price_name'], // 款项类目名称(购置税，上牌费用等)
            'purchase_order_sn' => $purchase_order_sn,
            'created_at' => dateTime(),
//            'settlement_sratus' => 1, // 结算状态 1 待结算 2 请款中 3 已结算 4 删除
            'approve_stauts' => 0, // 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
            'payroll_approve_sn' => $purchase_order_sn,
            'admin_id' => $adminId->id,
            'admin_name' => $adminId->nickname,
            'total_amount' => $kd['total_amount'],
            'module_type' => 1, // 模块类型 1 采购模块 2 车辆管理模块
        ];
        $res = WaMonthlySettlement::created($data_monthly_settlement);
        if (!$res) {
            return '创建月结款项数据失败';
        }
        return 'true';
    }

    public static function billDetailsByUpdate($param, $purchase_order_sn, $adminId, $supplier, &$bill_details_id)
    {
        $bill_details = $param['bill_details'];
        if ($bill_details) {
            foreach ($bill_details as $kd) {
                $bill_details_data = [
                    'purchase_order_sn' => $purchase_order_sn, //
                    'total_amount' => $kd['total_amount'], //
                    'price_name' => $kd['price_name'], //
                    'admin_id' => $adminId->id, //
                    'admin_name' => $adminId->nickname, //
                    'created_at' => dateTime(), //
                ];
                $monthly_sellement = ['检测报告费', '国内物流费', '国际快递费'];

                if ($kd['price_name'] && in_array($kd['price_name'], $monthly_sellement)) {
                    $bill_details_data['is_monthly_settlement'] = 2;
                    // 创建月结款项列表
                    $monthly_settlement_up = OrderPurchaseController::monthlySettlementByUpdate($param, $kd, $supplier, $purchase_order_sn, $adminId);
                    if (!$monthly_settlement_up != 'true') {
                        return $monthly_settlement_up;
                    }
                }

                $bill_details_id = WaOrdersPurchaseAmountDetail::created($bill_details_data); // 创建订单详情
                if (!$bill_details_id) {
                    return '添加采购订单账单明细失败';
                }
            }
        } else {
            return '采购费用，参数值为空';
        }
        return 'true';
    }

    public static function specsByUpdate($param, $order_data, $purchase_order_sn, &$specs, &$order_detail_id)
    {
        // 获取车型信息
        $specs = $param['specs_can'];//车型信息
        if ($specs) {


            $purchase_up_condition = [];
            $purchase_up_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $up_orders_purchase = WaOrdersPurchase::updated($order_data, $purchase_up_condition);
            if (!$up_orders_purchase) {
                return IndexController::errored('', '更新采购订单失败');

            }
            $del_opr = WaOrdersPurchaseRelevance::delete(['purchase_order_sn_parent' => $param['purchase_order_sn']]);
            foreach ($specs as $key) {
                $order_sn_child = 'WMCDZ' . IndexController::generateOrderSnOther(); // 子订单编号
                $order_purchase_up = OrderPurchaseController::childrenDetailDataByUpdate($param, $key, $purchase_order_sn, $order_sn_child, $order_detail_data);
                if ($order_purchase_up != 'true') {
                    return IndexController::errored('', $order_purchase_up);
                }

                $order_detail_id = WaOrdersPurchaseRelevance::created($order_detail_data); // 创建订单详情
                if (!$order_detail_id) {
                    return '更新采购单失败'.$order_detail_id;
                }

                // 更新销售订单代采购数量
                if (array_key_exists('order_sn_child', $key)) {
                    if ($key['order_sn_child']) {
                        $where_orders = [];
                        $where_orders [] = ['order_sn_child', '=', $key['order_sn_child']];
                        $order_child = WaOrdersRelevance::find($where_orders);
                        $order_child = json_decode($order_child);
                        if (!$order_child) {
                            return '销售订单产品信息获取失败'.$order_child;

                        }
                        if ($order_child->count) {

                            // 采购订单已采购数量
                            $where_purchase_count = [];
                            $where_purchase_count [] = ['order_sn_child', '=', $key['order_sn_child']];
                            $where_purchase_count [] = ['status', '!=', 7];
                            $sums_purchase_count = WaOrdersPurchaseRelevance::countPur($where_purchase_count);
                            if (!$sums_purchase_count) {
                                $sums_purchase_count = 0;
                            } else {
                                $sums_purchase_count = intval($sums_purchase_count);

                            }

                            // 总采购数量 intval($order_child->count)
                            // 待采购数量 intval($order_child->to_be_purchase_count)
                            // 当前采购数量 intval($key['count'])
                            $count = intval($order_child->count) - intval($sums_purchase_count);
                            if ($count < 0) {
                                $count = 0;
                                return '已采购数量超过销售订单总数量'.$order_child->count.'/'.$sums_purchase_count.'/'.$count;

                            }
                            if (intval($order_child->count) < intval($order_child->to_be_purchase_count)) {
                                return '待采购数量超过销售订单总数量'.$order_child->count.'/'.$order_child->to_be_purchase_count;

                            }
                            $where_order_relevance = [];
                            $where_order_relevance [] = ['order_sn_child', '=', $key['order_sn_child']];
                            $data_order_relevance = [
                                'to_be_purchase_count' => intval($count),
                                'updated_at' => dateTime(),
                            ];
                            $Orders_re_up = WaOrdersRelevance::updated($data_order_relevance, $where_order_relevance);
                            if (!$Orders_re_up) {
                                return '更新销售订单待采购数量失败'.$Orders_re_up;

                            }
                        }
                    }
                }
            }
            return 'true';

        } else {
            return '创建采购单失败，参数值为空';

        }
    }

    public static function orderToBePurchaseCoutUpdate($purchase_order_sn)
    {

        // 采购订单已采购数量
        $purchase_relevance_condition = [];
        $purchase_relevance_condition [] = ['purchase_order_sn_parent', '=', $purchase_order_sn];
        $purchase_relevance_data = WaOrdersPurchaseRelevance::all($purchase_relevance_condition);
        $purchase_relevance_data = json_decode($purchase_relevance_data);

        if ($purchase_relevance_data){
            foreach ($purchase_relevance_data as $key){
                // 返回采购订单中售订单代采购数量
                if ($key->order_sn_child) {

                    $where_orders = [];
                    $where_orders [] = ['order_sn_child', '=', $key->order_sn_child];
                    $order_child = WaOrdersRelevance::find($where_orders);
                    $order_child = json_decode($order_child);
                    if (!$order_child) {
                        $data_error = [
                            '错误：销售订单子订单数据查询',
                            '销售订单编号'.$key->order_sn_child,
                        ];
                        IndexController::logErrorNew('orderToBePurchaseCoutUpdate-model', $data_error);
                        return IndexController::errored('', '销售订单子订单数据查询');
                    }
                    if ($order_child->count) {

                        // 总采购数量 intval($order_child->count)
                        // 销售订单当前的待采购数量 intval($order_child->to_be_purchase_count)
                        // 当前退回的代采采购数量 intval($key->count)
                        $to_be_purchase_count_all = intval($order_child->to_be_purchase_count) + intval($key->count);
                        if (intval($order_child->count) < intval($to_be_purchase_count_all)) {
                            $to_be_purchase_count = $order_child->count;
                        }else{
                            $to_be_purchase_count = $to_be_purchase_count_all;

                        }
                        if (intval($order_child->count) < intval($order_child->to_be_purchase_count)) {
                            $data_error = [
                                '错误：待采购数量超过销售订单总数量',
                                '总数量和代采数量'.$order_child->count.'/'.$order_child->to_be_purchase_count,
                            ];
                            IndexController::logErrorNew('orderToBePurchaseCoutUpdate-model', $data_error);
                            return IndexController::errored('', '待采购数量超过销售订单总数量');

                        }
                        $where_order_relevance = [];
                        $where_order_relevance [] = ['order_sn_child', '=', $key->order_sn_child];
                        $data_order_relevance = [
                            'to_be_purchase_count' => intval($to_be_purchase_count),
                            'updated_at' => dateTime(),
                        ];
                        $Orders_re_up = WaOrdersRelevance::updated($data_order_relevance, $where_order_relevance);

                        if (!$Orders_re_up) {
                            $data_error = [
                                '错误：更新销售订单待采购数量失败',
                                '同步的代采数量和子订单编号'.$to_be_purchase_count.'/'.$key->order_sn_child,
                            ];
                            IndexController::logErrorNew('orderToBePurchaseCoutUpdate-model', $data_error);
                            return IndexController::errored('', '更新销售订单待采购数量失败');

                        }
                    }
                }
            }
        }

        return 'true';


    }


    /**
     * 指定采购订单操作人
     * @param Request $request
     * @return Response
     */
    public function updatePurchaseOperazione(Request $request)
    {

//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取采购订单编号
        if (!$param['purchase_order_sn']) {
            return IndexController::errored('1', '订单编号不能为空');
        }
        $indicare_qualcuno_by_operazione = '';
        if (array_key_exists('indicare_qualcuno_by_operazione',$param)){
            if ($param['indicare_qualcuno_by_operazione']) {
                $indicare_qualcuno_by_operazione = json_encode($indicare_qualcuno_by_operazione);
            }
        }
        \support\Db::beginTransaction();
        try {
            $purchase_condition = [];
            $purchase_condition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
            $purchase_condition_data = [
                'indicare_qualcuno_by_operazione' => $indicare_qualcuno_by_operazione,
                'updated_at' => dateTime(),
                ];
            $purchase_up_result = WaOrdersPurchase::updated($purchase_condition_data,$purchase_condition);
            if (!$purchase_up_result){
                return IndexController::errored('','采购操作人信息更新失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '采购操作人信息更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('updatePurchaseOrder', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored('', '采购操作人信息更新失败');

        }
    }


//
//    /**
//     * 创建采购订单 - 手动
//     * @param Request $request
//     * @return Response
//     * 订单创建人->下单用户->下了几款车型笔->多少量->从哪里发到哪里->中间产生了多少费用
//     */
//    public function createPurchaseOrder(Request $request)
//    {
////        process($request);
//        // 获取参数信息
//        $param = $request->all();
//        // 获取管理员信息
//        $adminId = json_decode(adminId($request));
//
//        \support\Db::beginTransaction();
//        try {
//            /**
//             * 创建采购订单编号
//             */
//            $purchase_order_sn = 'WMHTC' . IndexController::generateOrderSnOther();
//            $order_data['purchase_order_sn'] = $purchase_order_sn;
//
//            // 供应商信息
//            $supplier = WaSupplier::find(['id' => $param['supplier_id']]);
//            $supplier = json_decode($supplier);
//            if (!$supplier) {
//                return IndexController::errored('', '供应商信息获取失败，无法创建采购单');
//            }
//
//            // 采购订单数据的-入参参数
//            $order_data_add = OrderPurchaseController::dataByCreate($param, $supplier, $adminId, $purchase_order_sn, $order_data);
//            if ($order_data_add != true) {
//                return IndexController::errored('', $order_data_add);
//            }
//            // 车型信息 + (订单采购主订单 + 子订单 创建)
//            $specs_created = OrderPurchaseController::specsByCreate($param, $order_data, $purchase_order_sn, $order_detail_id);
//            if ($specs_created != true) {
//                return IndexController::errored('', $specs_created);
//            }
//            // 添加采购订单账单明细
//            $bill_details_add = OrderPurchaseController::billDetailsByCreate($param, $purchase_order_sn, $adminId, $supplier, $bill_details_id);
//            if ($bill_details_add != true) {
//                return IndexController::errored('', $bill_details_add);
//            }
//            if ($order_data && $order_detail_id && $bill_details_id) {
//                \support\Db::commit();
//                return IndexController::successed('', '采购单创建成功');
//            } else {
//                return IndexController::errored($order_data . '+++++' . $order_detail_id . '+++++' . $bill_details_id, '创建采购订单失败');
//            }
//
//        } catch (\Throwable $exception) {
//            IndexController::logError('createPurchaseOrder', $param, $adminId, $exception);
//            \support\Db::rollBack();
//            return IndexController::errored($exception, '创建采购订单失败');
//        }
//    }
//
//    public static function dataByCreate($param, $supplier, $adminId, $purchase_order_sn, &$order_data)
//    {
//        if ($param['registration_company_id']) {
//            $registration_condition = [];
//            $registration_condition [] = ['id', '=', $param['registration_company_id']];
//            $regist_rationCompany = WaRegistrationCompany::find($registration_condition);
//            if (!$regist_rationCompany) {
//                return '上牌公司信息为空';
//            }
//            $registration_company_id = $param['registration_company_id'];
//        } else {
//            $registration_company_id = 0;
////            return '上牌公司id为必填';
//        }
//
//        $order_data = [
//            // 采购单产品字段 公共字段
//            'purchase_orders_status' => 0, // 采购单状态 0 草稿 1审批中 2待签署审批合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
//            'created_at' => dateTime(), // 创建时间
//            'supplier_id' => $param['supplier_id'], // 供应商id
//            'supplier_name' => $supplier->name, // 供应商名字
//            'supplier_credit_code' => $supplier->credit_code, // 组织机构信用代码
//            'supplier_linkman' => $supplier->linkman, // 联系人
//            'supplier_phone' => $supplier->phone, // 联系电话
//            'supplier_email' => $supplier->email, // 邮箱
//            'supplier_province' => $supplier->province, // 省份
//            'supplier_city' => $supplier->city, // 市
//            'supplier_main_brand' => $supplier->main_brand, // 供应商主营品牌
//            'supplier_type' => 1, // 供应商类型
//            'purchase_order_sn' => $purchase_order_sn, //
//            'admin_id' => $adminId->id, // 创建人id
//            'admin_name' => $adminId->nickname, // 创建人名称
//            'contract_price' => $param['contract_price'], // 合同金额
//
//
//            'delivery_province' => $param['delivery_province'], // 交付地点-省
//            'delivery_city' => $param['delivery_city'], // 交付地点-市
//            'deposit_price' => $param['deposit_price'], // 定金金额
//            'deposit_ratio' => $param['deposit_ratio'], // 定金比例
//            'supplementary_terms' => $param['supplementary_terms'], // 补充条款
////            'delivery_accessories' => $param['delivery_accessories'], // 交车附件
//
//            'registration_company_id' => $registration_company_id, // 上牌公司id
//            'registration_company_name' => $param['registration_company_name'], // 上牌公司名字
//            'is_mine_registration_company' => $param['is_mine_registration_company'], // 是否自己的牌照挂靠公司 1 是 2 不是
////            'transfer_export_company_id' => $param['transfer_export_company_id'], // 出口公司id
////            'transfer_export_company_name' => $param['transfer_export_company_name'], // 出口公司名字
//
//            'registration_company_province' => $param['registration_company_province'], //挂牌公司-省份
//            'registration_company_city' => $param['registration_company_city'], //挂牌公司-市
////            'transfer_export_company_province' => $param['transfer_export_company_province'], //出口公司-省份
////            'transfer_export_company_city' => $param['transfer_export_company_city'], //出口公司-市
//
//            'registration_credit_code' => $param['registration_credit_code'], //挂靠公司-组织机构信用代码
////            'transfer_export_credit_code' => $param['transfer_export_credit_code'], //出口公司-组织机构信用代码
//
//
//        ];
//
//        if (array_key_exists('registration_company_info', $param)) {
//            if ($param['registration_company_info']){
//                $order_data['registration_company_info'] = json_encode($param['registration_company_info']);
//            }
//        }
//        if (array_key_exists('latest_delivery_time', $param)) {
//            if ($param['latest_delivery_time']) {
//                $order_data['latest_delivery_time'] = $param['latest_delivery_time'];// 最晚交付时间
//            }
//        }
//
//        return 'true';
//    }
//
//    public static function childrenDetailDataByCreate($param, $key, $purchase_order_sn, $order_sn_child, &$order_detail_data)
//    {
//
//        $deposit_total_price = $key['deposit_total_price'];
//
//        $order_detail_data = [
//            'guide_price' => $key['guide_price'], // 指导价
//            'purchase_order_sn_parent' => $purchase_order_sn, // 采购单父订单编号
//            'purchase_order_sn_child' => $order_sn_child, // 子订单编号
//            'brands_name' => $key['brands_name'], // 品牌
//            'series_name' => $key['series_name'], // 车系
//            'model' => $key['model'], // 车型名称
//            'retail_concessions' => $key['retail_concessions'], // 零点优惠
//            'purchase_quotation' => $key['purchase_quotation'], // 车辆采购价格/采购报价
//            'count' => $key['count'], // 数量
//            'supplier_id' => $param['supplier_id'], // 供应商id
//            'created_at' => dateTime(), // 创建时间
//
//
//            'other_concessions' => '', // 其它优惠
//            'vehicle_status' => $key['vehicle_status'], // 车辆状况(是否是新车)  1 新车 2 二手车
//            'sub_brand_name' => $key['sub_brand_name'], // 厂商
//            'market_time' => $key['market_time'], // 上市日期
//            'is_nev' => $key['is_nev'], // 是否是新能源
//            'seat_count' => $key['seat_count'], // 车座数
//            'purchase_price' => $key['purchase_price'], // 二手车采购价格
//            'VAT_invoice_price' => $key['VAT_invoice_price'], // 增值税发票金额
//            'other_rebates' => $key['other_rebates'], // 采购返利
////            'registration_province' => $key['registration_province'], // 上牌省份
////            'registration_city' => $key['registration_city'], // 上牌市区
////            'registration_id' => $key['registration_id'], // 上牌服务商id
////
////            'transfer_export_province' => $key['transfer_export_province'], // 转移待出口省份
////            'transfer_export_city' => $key['transfer_export_city'], // 转移待出口市区
////            'transfer_export_id' => $key['transfer_export_id'], // 转移待出口服务商id
//
//            'purchase_single_quotation' => $key['purchase_single_quotation'], // 采购单价
//
//            'car_year' => $key['car_year'], //  车辆年款
//            'jb' => $key['jb'], // 级别
//            'series_type' => $key['series_type'], // 车身类型
//            'driver_form' => $key['driver_form'], // 驱动方式
//            'length' => $key['length'], // 长
//            'width' => $key['width'], // 宽
//            'height' => $key['height'], // 高
//            'curb_weight' => $key['curb_weight'], // 设计重量
//
//
//            'deposit_single_price' => $deposit_total_price / $key['count'], // 定金单价金额
//            'deposit_total_price' => $deposit_total_price, // 定金总价金额
//            'purchase_single_quotation' => $key['purchase_single_quotation'], // 车辆采购单价金额
//            'purchase_total_price' => $key['purchase_total_price'], // 车辆采购总价金额(原来是 total_price 字段现在修改成此字段 )
//            'resource_service_fee' => $key['resource_service_fee'], // 资源服务费
//            'is_drawback' => $key['is_drawback'], // 是否退税
//            'is_CLIVTA' => $key['is_CLIVTA'], // 是否交强险  文森说的 要大些
//        ];
//        if ($key['other_price']){
//            $order_detail_data['other_price'] = json_encode($key['other_price']);// 其它费用
//        }
//
//        if ($key['option_package']){
//            $order_detail_data['option_package'] = json_encode($key['option_package']);// 选装包
//        }
//
//        if ($key['price_options']){
//            $order_detail_data['price_options'] = json_encode($key['price_options']);// 费用选项
//        }
//        if (array_key_exists('invoice_price',$key)){
//            if ($key['invoice_price']){
//                $order_detail_data['invoice_price'] = $key['invoice_price']; // 机动车专用发票价
//            }
//        }
//
//        if (array_key_exists('color_interior', $key)) {
//            $order_detail_data['color_interior'] = $key['color_interior']; // 内饰颜色
//        }
//        if (array_key_exists('color_exterior', $key)) {
//            $order_detail_data['color_exterior'] = $key['color_exterior']; // 外观颜色
//        }
//        return 'true';
//    }
//
//    public static function monthlySettlementByCreate($param, $kd, $supplier, $purchase_order_sn, $adminId)
//    {
//        if ($kd['price_name'] == '检测报告费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '国内物流费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '国际快递费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '上牌费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '购置税') {
//            $type = 999;
//        }
//        $data_monthly_settlement = [
//            'type' => $type,
//            'supplier_id' => $param['supplier_id'],
//            'supplier_name' => $supplier->name,
//            'price_name' => $kd['price_name'], // 款项类目名称(购置税，上牌费用等)
//            'purchase_order_sn' => $purchase_order_sn,
//            'created_at' => dateTime(),
////            'settlement_sratus' => 1, // 结算状态 1 待结算 2 请款中 3 已结算 4 删除
//            'approve_stauts' => 0, // 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
//            'payroll_approve_sn' => $purchase_order_sn,
//            'admin_id' => $adminId->id,
//            'admin_name' => $adminId->nickname,
//            'total_amount' => $kd['total_amount'],
//            'module_type' => 1, // 模块类型 1 采购模块 2 车辆管理模块
//        ];
//        $res = WaMonthlySettlement::created($data_monthly_settlement);
//        if (!$res) {
//            return '创建月结款项数据失败';
//        }
//        return 'ture';
//    }
//
//    public static function billDetailsByCreate($param, $purchase_order_sn, $adminId, $supplier, &$bill_details_id)
//    {
//        $bill_details = $param['bill_details'];
//        if ($bill_details) {
//            foreach ($bill_details as $kd) {
//                $bill_details_data = [
//                    'purchase_order_sn' => $purchase_order_sn, //
//                    'total_amount' => $kd['total_amount'], //
//                    'price_name' => $kd['price_name'], //
//                    'admin_id' => $adminId->id, //
//                    'admin_name' => $adminId->nickname, //
//                    'created_at' => dateTime(), //
//                ];
//                $monthly_sellement = ['检测报告费', '国内物流费', '国际快递费'];
//
//                if ($kd['price_name'] && in_array($kd['price_name'], $monthly_sellement)) {
//                    $bill_details_data['is_monthly_settlement'] = 2;
//                    // 创建月结款项列表
//                    $settlement_add = OrderPurchaseController::monthlySettlementByCreate($param, $kd, $supplier, $purchase_order_sn, $adminId);
//                    if ($settlement_add != 'true') {
//                        return IndexController::errored('', $settlement_add);
//                    }
//                }
//
//                $bill_details_id = WaOrdersPurchaseAmountDetail::created($bill_details_data); // 创建订单详情
//                if (!$bill_details_id) {
//                    return '添加采购订单账单明细失败';
//                }
//            }
//        } else {
//            return '采购费用，参数值为空';
//        }
//        return 'true';
//    }
//
//    public static function specsByCreate($param, $order_data, $purchase_order_sn, &$order_detail_id)
//    {
//        $specs = $param['specs_can'];//车型信息
//
//        if ($specs) {
//            // 主采购单字段
//            $orders_purchase_id = WaOrdersPurchase::created($order_data); // 创建采购单
//            if (!$orders_purchase_id) {
//                return IndexController::errored('', '创建采购单失败');
//            }
//            foreach ($specs as $key) {
//                $order_sn_child = 'WMCDZ' . IndexController::generateOrderSnOther(); // 子订单编号
//                //采购订单子订单入参数据
//                $order_detail_data_check = OrderPurchaseController::childrenDetailDataByCreate($param, $key, $purchase_order_sn, $order_sn_child, $order_detail_data);
//                if ($order_detail_data_check != 'true') {
//                    return IndexController::errored('', '日志添加失败失败');
//                }
//
//                if (array_key_exists('order_sn_child', $key)) {
//                    $condtion_order = [];
//                    $condtion_order [] = ['order_sn_child', '=', $key['order_sn_child']];
//                    $condtion_order_data = WaOrdersRelevance::find($condtion_order);
//                    $condtion_order_data = json_decode($condtion_order_data);
//                    if ($condtion_order_data) {
//                        $order_detail_data['order_sn_child'] = $condtion_order_data->order_sn_child;
//                        $order_detail_data['order_sn_parent'] = $condtion_order_data->order_sn_parent;
//                    }
//                }
//                $order_detail_id = WaOrdersPurchaseRelevance::created($order_detail_data); // 创建订单详情
//                if (!$order_detail_id) {
//                    return IndexController::error_by_static($order_detail_id, '创建报价单失败');
//                }
//
//                // 更新采购订单的定金总额
//                $purchase_amount_condition = [];
//                $purchase_amount_condition [] = ['purchase_order_sn_parent', '=', $purchase_order_sn];
//                $deposit_price = WaOrdersPurchaseRelevance::sumByDeposit($purchase_amount_condition); // 定金总价金额
//                $total_amount = WaOrdersPurchaseRelevance::sumByPurchaseTotalPrice($purchase_amount_condition); // 采购车辆总价
//                $balance_total_price = round($total_amount, 2) - round($deposit_price, 2);  // 采购订单尾款
//                $purchase_order_up_condition = [];
//                $purchase_order_up_condition [] = ['purchase_order_sn', '=', $purchase_order_sn];
//                $condtion_order_purchase_data = [
//                    'deposit_price' => round($deposit_price, 2),
//                    'total_amount' => round($total_amount, 2),
//                    'balance_total_price' => round($balance_total_price, 2),
//                    'updated_at' => dateTime(),
//                ];
//                $condtion_order_purchase_up = WaOrdersPurchase::updated($condtion_order_purchase_data, $purchase_order_up_condition);
//                if (!$condtion_order_purchase_up) {
//                    return IndexController::error_by_static($order_detail_id, '创建采购订单定金价格更新失败');
//                }
//
//                if (array_key_exists('order_sn_child', $key)) {
//                    $where_dec = [];
//                    $where_dec [] = ['order_sn_child', '=', $key['order_sn_child']];
//                    $where_dec [] = ['model', '=', $key['model']];
//                    $decrement = WaOrdersRelevance::decrement($where_dec, $key['count']);
//                    if (!$decrement) {
//                        return IndexController::error_by_static($order_detail_id, '订单详情的产品数量递减失败');
//                    }
//                }
//            }
//
//        } else {
//            return IndexController::error_by_static($specs, '创建采购单失败，参数值为空');
//        }
//        return $order_detail_id;
//    }
//
//
//    /**
//     * 更新采购订单
//     * @param Request $request
//     * @return Response
//     */
//    public function updatePurchaseOrder(Request $request)
//    {
//
////        process($request);
//        // 获取参数信息
//        $param = $request->all();
//        // 获取管理员信息
//        $adminId = json_decode(adminId($request));
//        // 获取采购订单编号
//        if (!$param['purchase_order_sn']) {
//            return IndexController::errored('1', '订单编号不能为空');
//        }
//        \support\Db::beginTransaction();
//        try {
//
//
////        $purchase_order_sn = 'WMHTC'.IndexController::generateOrderSn(); // 采购订单编号
////        $order_data['purchase_order_sn'] = $purchase_order_sn; // 采购订单编号
//            // 供应商信息
//            $supplier = WaSupplier::find(['id' => $param['supplier_id']]);
//            $supplier = json_decode($supplier);
//            if (!$supplier) {
//                return IndexController::errored('2', '供应商信息获取失败，无法创建采购单');
//            }
//
//            // 创建采购订单数据的-入参参数
//            $order_data_up = OrderPurchaseController::dataByUpdate($param, $supplier, $adminId, $order_data);
//            if ($order_data_up != 'true') {
//                return IndexController::errored('3', $order_data_up);
//            }
//            //车型信息 + (订单采购主订单 + 子订单 更新)
//            $specs_up = OrderPurchaseController::specsByUpdate($param, $order_data, $param['purchase_order_sn'], $specs, $order_detail_id);
//            if ($specs_up != 'true') {
//                return IndexController::errored('4', $specs_up);
//            }
//            // 删除账单明细旧数据
//            $where_bill_details = [];
//            $where_bill_details [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
//            $bill_del = WaOrdersPurchaseAmountDetail::deleted($where_bill_details);
//            //删除该笔采购订单的月结账单
//            $where_monthly_settlement = [];
//            $where_monthly_settlement [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
//            $monthly_del = WaMonthlySettlement::deleted($where_monthly_settlement);
//            /**
//             * 添加采购订单账单明细
//             */
//            $bill_details_up = OrderPurchaseController::billDetailsByUpdate($param, $param['purchase_order_sn'], $adminId, $supplier, $bill_details_id);
//            if ($bill_details_up != 'true') {
//                return IndexController::errored('5', $bill_details_up);
//            }
//            \support\Db::commit();
//            return IndexController::successed('', '采购单更新成功');
//        } catch (\Throwable $exception) {
//            IndexController::logError('updatePurchaseOrder', $param, $adminId, $exception);
//            \support\Db::rollBack();
//            return IndexController::errored('', '采购单更新失败');
//
//        }
//    }
//
//    public static function dataByUpdate($param, $supplier, $adminId, &$order_data)
//    {
//        $registration_company_id = ''; // 非我司没有id
//        if (array_key_exists('registration_company_id',$param)){
//            if ($param['registration_company_id']) {
//                $registration_condition = [];
//                $registration_condition [] = ['id', '=', $param['registration_company_id']];
//                $regist_rationCompany = WaRegistrationCompany::find($registration_condition);
//                $registration_company_id = $param['registration_company_id'];
//            }else{
//                $registration_company_id = 0;
//            }
//        }
//
//
//        $order_data = [
//            // 采购单产品字段 公共字段
//            'purchase_orders_status' => 0, // 采购单状态 0 草稿 1审批中 2待签署审批合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
//            'supplier_id' => $param['supplier_id'], // 供应商id
//            'supplier_name' => $supplier->name, // 供应商名字
//            'supplier_credit_code' => $supplier->credit_code, // 组织机构信用代码
//            'supplier_linkman' => $supplier->linkman, // 联系人
//            'supplier_phone' => $supplier->phone, // 联系电话
//            'supplier_email' => $supplier->email, // 邮箱
//            'supplier_province' => $supplier->province, // 省份
//            'supplier_city' => $supplier->city, // 市
//            'supplier_main_brand' => $supplier->main_brand, // 市
//            'admin_id' => $adminId->id, // 创建人id
//            'admin_name' => $adminId->nickname, // 创建人名称
//
//
//            'delivery_province' => $param['delivery_province'], // 交付地点-省
//            'delivery_city' => $param['delivery_city'], // 交付地点-市
//            'contract_price' => $param['contract_price'], // 合同金额
//            'deposit_price' => $param['deposit_price'], // 定金金额
//            'deposit_ratio' => $param['deposit_ratio'], // 定金比例
//            'supplementary_terms' => $param['supplementary_terms'], // 补充条款
////            'delivery_accessories' => $param['delivery_accessories'], // 交车附件
//            'updated_at' => dateTime(), // 更新订单
//
//
//            'registration_company_id' => $registration_company_id, // 上牌公司id
//            'registration_company_name' => $param['registration_company_name'], // 上牌公司名字
//            'is_mine_registration_company' => $param['is_mine_registration_company'], // 是否自己的牌照挂靠公司 1 是 2 不是
////            'transfer_export_company_id' => $param['transfer_export_company_id'], // 出口公司id
////            'transfer_export_company_name' => $param['transfer_export_company_name'], // 出口公司名字
//
//            'registration_company_province' => $param['registration_company_province'], //挂牌公司-省份
//            'registration_company_city' => $param['registration_company_city'], //挂牌公司-市
////            'transfer_export_company_province' => $param['transfer_export_company_province'], //出口公司-省份
////            'transfer_export_company_city' => $param['transfer_export_company_city'], //出口公司-市
//            'registration_credit_code' => $param['registration_credit_code'], //挂靠公司-组织机构信用代码
////            'transfer_export_credit_code' => $param['transfer_export_credit_code'], //出口公司-组织机构信用代码
//
//        ];
//
//        if (array_key_exists('registration_company_info', $param)) {
//            $order_data['registration_company_info'] = json_encode($param['registration_company_info']);
//        }
//
//        if (array_key_exists('transfer_export_company_info', $param)) {
//            $order_data['transfer_export_company_info'] = json_encode($param['transfer_export_company_info']);
//        }
//
//
//        if (array_key_exists('latest_delivery_time', $param)) {
//            if ($param['latest_delivery_time']) {
//                $order_data['latest_delivery_time'] = $param['registration_company_info'];// 最晚交付时间
//            }
//        }
//
//        return 'true';
//    }
//
//    public static function childrenDetailDataByUpdate($param, $key, $purchase_order_sn, $order_sn_child, &$order_detail_data)
//    {
//        $deposit_total_price = 0;
//        if (array_key_exists('deposit_single_price', $key)) {
//
//            if ($key['deposit_single_price'] && $key['deposit_single_price'] != 0) {
//                $deposit_total_price = $key['deposit_single_price'] * $key['count'];
//            }
//        }
//
//        $order_detail_data = [
//            'guide_price' => $key['guide_price'], // 指导价
//            'purchase_order_sn_parent' => $purchase_order_sn, // 采购单父订单编号
//            'purchase_order_sn_child' => $order_sn_child, // 子订单编号
////            'product_type' => $key['product_type'], // 产品类型
////            'car_type' => $key['car_type'], // 汽车类型 car_type 1轿车 2 SUV 3 MPV 4 跑车 5新能源
//            'brands_name' => $key['brands_name'], // 品牌
//            'series_name' => $key['series_name'], // 车系
//            'model' => $key['model'], // 车型名称
//            'retail_concessions' => $key['retail_concessions'], // 零点优惠
//            'purchase_quotation' => $key['purchase_quotation'], // 车辆采购价格/采购报价
//            'count' => $key['count'], // 数量
////            'total_price' => $key['total_price'], // 总价
//            'supplier_id' => $param['supplier_id'], // 供应商id
//            'created_at' => dateTime(), // 创建时间
//            'other_price' => json_encode($key['other_price']), // 其它费用
//
//            'vehicle_status' => $key['vehicle_status'], // 车辆状况(是否是新车)  1 新车 2 二手车
//
//
//
//
//            'transfer_export_province' => $key['transfer_export_province'], // 转移待出口省份
//            'transfer_export_city' => $key['transfer_export_city'], // 转移待出口市区
//            'transfer_export_id' => $key['transfer_export_id'], // 转移待出口服务商id
//            'option_package' => json_encode($key['option_package']), // 选装包
//            'price_options' => json_encode($key['price_options']), // 费用选项
//            'sub_brand_name' => $key['sub_brand_name'], // 厂商
//            'deposit_total_price' => $deposit_total_price, // 定金总价金额
//            'car_year' => $key['car_year'], //  车辆年款
//            'purchase_price' => $key['purchase_price'], // 二手车采购价格
//            'purchase_single_quotation' => $key['purchase_single_quotation'], // 车辆采购单价金额
//            'other_rebates' => $key['other_rebates'], // 采购返利
//            'purchase_total_price' => $key['purchase_total_price'], // 车辆采购总价金额(原来是 total_price 字段现在修改成此字段 )
//            'resource_service_fee' => $key['resource_service_fee'], // 资源服务费
//            'is_drawback' => $key['is_drawback'], // 是否退税
//            'is_CLIVTA' => $key['is_CLIVTA'], // 是否交强险  文森说的 要大些
//            'is_nev' => $key['is_nev'], // 是否是新能源
//            'deposit_single_price' => $key['deposit_single_price'], // 定金单价金额
//
//        ];
//
//        if (array_key_exists('color_interior', $key)) {
//            $order_detail_data['color_interior'] = $key['color_interior']; // 内饰颜色
//        }
//        if (array_key_exists('color_exterior', $key)) {
//            $order_detail_data['color_exterior'] = $key['color_exterior']; // 外观颜色
//        }
//        if (array_key_exists('order_sn_child', $key)) {
//            $order_detail_data['order_sn_child'] = $key['order_sn_child']; // 外观颜色
//        }
//        if (array_key_exists('order_sn_parent', $key)) {
//            $order_detail_data['order_sn_parent'] = $key['order_sn_parent']; // 外观颜色
//        }
//
//        if (array_key_exists('invoice_price',$key)){
//            if ($key['invoice_price']){
//                $order_detail_data['invoice_price'] = $key['invoice_price']; // 机动车专用发票价
//            }
//        }
//
//        return 'true';
//    }
//
//    public static function monthlySettlementByUpdate($param, $kd, $supplier, $purchase_order_sn, $adminId)
//    {
//
//        if ($kd['price_name'] == '检测报告费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '国内物流费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '国际快递费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '上牌费') {
//            $type = 999;
//        } elseif ($kd['price_name'] == '购置税') {
//            $type = 999;
//        }
//        $data_monthly_settlement = [
//            'type' => $type,
//            'supplier_id' => $param['supplier_id'],
//            'supplier_name' => $supplier->name,
//            'price_name' => $kd['price_name'], // 款项类目名称(购置税，上牌费用等)
//            'purchase_order_sn' => $purchase_order_sn,
//            'created_at' => dateTime(),
////            'settlement_sratus' => 1, // 结算状态 1 待结算 2 请款中 3 已结算 4 删除
//            'approve_stauts' => 0, // 审批状态 0 待审批 1 审批中 2 审批通过 3 审批驳回
//            'payroll_approve_sn' => $purchase_order_sn,
//            'admin_id' => $adminId->id,
//            'admin_name' => $adminId->nickname,
//            'total_amount' => $kd['total_amount'],
//            'module_type' => 1, // 模块类型 1 采购模块 2 车辆管理模块
//        ];
//        $res = WaMonthlySettlement::created($data_monthly_settlement);
//        if (!$res) {
//            return '创建月结款项数据失败';
//        }
//        return 'true';
//    }
//
//    public static function billDetailsByUpdate($param, $purchase_order_sn, $adminId, $supplier, &$bill_details_id)
//    {
//        $bill_details = $param['bill_details'];
//        if ($bill_details) {
//            foreach ($bill_details as $kd) {
//                $bill_details_data = [
//                    'purchase_order_sn' => $purchase_order_sn, //
//                    'total_amount' => $kd['total_amount'], //
//                    'price_name' => $kd['price_name'], //
//                    'admin_id' => $adminId->id, //
//                    'admin_name' => $adminId->nickname, //
//                    'created_at' => dateTime(), //
//                ];
//                $monthly_sellement = ['检测报告费', '国内物流费', '国际快递费'];
//
//                if ($kd['price_name'] && in_array($kd['price_name'], $monthly_sellement)) {
//                    $bill_details_data['is_monthly_settlement'] = 2;
//                    // 创建月结款项列表
//                    $monthly_settlement_up = OrderPurchaseController::monthlySettlementByUpdate($param, $kd, $supplier, $purchase_order_sn, $adminId);
//                    if (!$monthly_settlement_up != 'true') {
//                        return $monthly_settlement_up;
//                    }
//                }
//
//                $bill_details_id = WaOrdersPurchaseAmountDetail::created($bill_details_data); // 创建订单详情
//                if (!$bill_details_id) {
//                    return '添加采购订单账单明细失败';
//                }
//            }
//        } else {
//            return '采购费用，参数值为空';
//        }
//        return 'true';
//    }
//
//    public static function specsByUpdate($param, $order_data, $purchase_order_sn, &$specs, &$order_detail_id)
//    {
//        // 获取车型信息
//        $specs = $param['specs_can'];//车型信息
//        if ($specs) {
//
//
//            $purchase_up_condition = [];
//            $purchase_up_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
//            $up_orders_purchase = WaOrdersPurchase::updated($order_data, $purchase_up_condition);
//            if (!$up_orders_purchase) {
//                return IndexController::errored('', '更新采购订单失败');
//
//            }
//            $del_opr = WaOrdersPurchaseRelevance::delete(['purchase_order_sn_parent' => $param['purchase_order_sn']]);
//            foreach ($specs as $key) {
//                $order_sn_child = 'WMCDZ' . IndexController::generateOrderSnOther(); // 子订单编号
//                $order_purchase_up = OrderPurchaseController::childrenDetailDataByUpdate($param, $key, $purchase_order_sn, $order_sn_child, $order_detail_data);
//                if ($order_purchase_up != 'true') {
//                    return IndexController::errored('', $order_purchase_up);
//                }
//
//                $order_detail_id = WaOrdersPurchaseRelevance::created($order_detail_data); // 创建订单详情
//                if (!$order_detail_id) {
//                    return '更新采购单失败'.$order_detail_id;
//                }
//
//                // 更新销售订单代采购数量
//                if (array_key_exists('order_sn_child', $key)) {
//                    if ($key['order_sn_child']) {
//                        $where_orders = [];
//                        $where_orders [] = ['order_sn_child', '=', $key['order_sn_child']];
//                        $order_child = WaOrdersRelevance::find($where_orders);
//                        $order_child = json_decode($order_child);
//                        if (!$order_child) {
//                            return '销售订单产品信息获取失败'.$order_child;
//
//                        }
//                        if ($order_child->count) {
//
//                            // 采购订单已采购数量
//                            $where_purchase_count = [];
//                            $where_purchase_count [] = ['order_sn_child', '=', $key['order_sn_child']];
//                            $where_purchase_count [] = ['status', '!=', 7];
//                            $sums_purchase_count = WaOrdersPurchaseRelevance::countPur($where_purchase_count);
//                            if (!$sums_purchase_count) {
//                                $sums_purchase_count = 0;
//                            } else {
//                                $sums_purchase_count = intval($sums_purchase_count);
//
//                            }
//
//                            // 总采购数量 intval($order_child->count)
//                            // 待采购数量 intval($order_child->to_be_purchase_count)
//                            // 当前采购数量 intval($key['count'])
//                            $count = intval($order_child->count) - intval($sums_purchase_count);
//                            if ($count < 0) {
//                                $count = 0;
//                                return '已采购数量超过销售订单总数量'.$order_child->count.'/'.$sums_purchase_count.'/'.$count;
//
//                            }
//                            if (intval($order_child->count) < intval($order_child->to_be_purchase_count)) {
//                                return '待采购数量超过销售订单总数量'.$order_child->count.'/'.$order_child->to_be_purchase_count;
//
//                            }
//                            $where_order_relevance = [];
//                            $where_order_relevance [] = ['order_sn_child', '=', $key['order_sn_child']];
//                            $data_order_relevance = [
//                                'to_be_purchase_count' => intval($count),
//                                'updated_at' => dateTime(),
//                            ];
//                            $Orders_re_up = WaOrdersRelevance::updated($data_order_relevance, $where_order_relevance);
//                            if (!$Orders_re_up) {
//                                return '更新销售订单待采购数量失败'.$Orders_re_up;
//
//                            }
//                        }
//                    }
//                }
//            }
//            return 'true';
//
//        } else {
//            return '创建采购单失败，参数值为空';
//
//        }
//    }


    /**
     * 更新-采购订单状态
     * @param Request $request
     * @return Response
     */
    public function updatePurchaseOrderStatus(Request $request)
    {
//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 查看订单状态

        $status = self::status($param['purchase_order_sn']);
        // 根据采购单编号获取订单信息
        $orders = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取采购单信息失败');
        }

        \support\Db::beginTransaction();
        try {
            // 订单审批类型 1供应商审批 2销售订单审批 3销售合同审批 4采购订单审批 5采购合同审批 6采购请款审批 7交强险请款审批
            PublicCommentController::采购订单状态;// 采购订单状态
            if ($param['purchase_orders_status'] == 0) {
                if (!in_array($orders->purchase_orders_status, [1, 9])) {
                    return IndexController::errored('', '只有 审批中 和 审批驳回 状态 才可以撤回草稿');
                }
                // 0 草稿 退回草稿 ->撤回审批:
                // 采购单回到草稿状态
//                WaOrdersPurchase::updated(['purchase_order_sn' => $param['purchase_order_sn']],['purchase_orders_status' => 0,'updated_at' => dateTime()]); // 待审批
                // 采购审批单 审批状态变成已撤回
                if ($orders->purchase_orders_status == 1) {
                    $up_approve = WaPurchaseOrdersExamineApprove::updated(['purchase_order_sn' => $param['purchase_order_sn']], ['status' => 3, 'updated_at' => dateTime()]);
                    if (!$up_approve) {
                        return IndexController::errored('', '撤回草稿->审批状态修改失败');
                    }
                }

                // 采购审批日志 添加审批驳回记录
                $check = WaPurchaseOrdersExamineApprove::find($adminId, ['purchase_order_sn' => $param['purchase_order_sn'], 'po_no' => $orders->po_no]);
                $check = json_decode($check);
                if (!$check) {
                    return IndexController::errored('', '无法获取该订单的审批数据');
                }
                $approve_log_data = [
                    'po_no' => $check->po_no, // 采购订单编号
                    'check_id' => $check->id, // 审批id
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'status' => 3, //待审批 1审批通过 2 审批驳回 3 撤回 4  删除
                    'refuse_reason' => '审批驳回',
                ];
                if ($orders->purchase_orders_status == 1) {
                    $approve_log_data['refuse_reason'] = '撤回审批';
                    $approve_log_data['status'] = 3;

                } elseif ($orders->purchase_orders_status == 9) {
                    $approve_log_data['refuse_reason'] = '审批驳回->撤回草稿';
                    $approve_log_data['status'] = 2;
                }

                if ($param['purchase_order_sn']) {
                    $approve_log_data['purchase_order_sn'] = $param['purchase_order_sn'];// 采购订单编号
                }
                $res = WaPurchaseOrdersExamineApproveFlow::create($approve_log_data);
                if (!$res) {
                    return IndexController::errored('', '审批流记录创建失败失败');
                }
            } elseif ($param['purchase_orders_status'] == 1) {

                return IndexController::errored('', '有单独的提交审批接口');
            } elseif ($param['purchase_orders_status'] == 2) {
                // 2待签署审批合同
                return IndexController::errored('', '订单审批通过后转为待签署审批合同状态');
            } elseif ($param['purchase_orders_status'] == 3) {
                //3 进行中 确认签署合同 -> 进行中
                if ($status != 2) {
                    return IndexController::errored('', '待签署审批合同状态下才能修改');
                }
            } elseif ($param['purchase_orders_status'] == 4) {
                //4 待供应商开票
                if ($status != 3) {
                    return IndexController::errored('', '待采购请款状态下才能修改');
                }
                return IndexController::errored('', '在单独的接口处理');
            } elseif ($param['purchase_orders_status'] == 5) {
                //5 待配车
                if ($status != 4) {
                    return IndexController::errored('', '在单独的接口处理');
                }
            } elseif ($param['purchase_orders_status'] == 6) {
                //6已完成
                if ($status != 5) {
                    return IndexController::errored('', '待配车状态下才能修改');
                }
            } elseif ($param['purchase_orders_status'] == 7) {
                //7已作废
                if ($status) {
                    if (!in_array(intval($status), [2, 3, 4, 5, 6])) {
                        return IndexController::errored('', '不是可作废状态');
                    }

                }

                // 采购订单作废 子订单也要作废  否则会影响销售订单待采购数量数据
                $purchase_relevance_condition = [];
                $purchase_relevance_condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
                $purchase_relevance_data = [
                    'status' => 7,
                    'updated_at' => dateTime(),
                ];
                $purchase_relevance_up = WaOrdersPurchaseRelevance::updated($purchase_relevance_data, $purchase_relevance_condition);
                $purchase_relevance_up = json_decode($purchase_relevance_up);
                if (!$purchase_relevance_up){
                    return IndexController::errored('', '采购订单子订单状态同步失败');
                }

                // 获取审批信息 用于添加日志记录
                $check_condition = [];
                $check_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
                $check = WaPurchaseOrdersExamineApprove::find($adminId, $check_condition);
                $check = json_decode($check);
                if ($check) {
                    $approve_status = WaPurchaseOrdersExamineApprove::updated(['purchase_order_sn' => $param['purchase_order_sn']], ['status' => 3, 'updated_at' => dateTime()]);
                    if (!$approve_status) {
                        return IndexController::errored('', '修改审批状态为撤回审批驳回');
                    }
                    //修改审批状态为撤回审批
                    $approve_log_data = [
                        'po_no' => $check->po_no, // 采购订单编号
                        'check_id' => $check->id, // 审批id
                        'check_admin_type' => 0, // 1 主管审批  2 部门所有人中的任何一个  （撤回的时候可以是0）
                        'created_at' => dateTime(),
                        'admin_id' => $adminId->id,
                        'admin_name' => $adminId->nickname,
                        'status' => 3, //待审批 1审批通过 2 审批驳回 3 撤回 4  删除
                        'refuse_reason' => '作废',
                        'purchase_order_sn' => $param['purchase_order_sn'],
                    ];
                    $res = WaPurchaseOrdersExamineApproveFlow::create($approve_log_data);
                    if (!$res) {
                        return IndexController::errored('', '添加日志记录失败');
                    }
                }

//                return IndexController::successed($res, '状态已更新');

                // 销售订单代采购数量 返还
                $purchase_relevance_condition = [];
                $purchase_relevance_condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
                $purchase_relevance_data = WaOrdersPurchaseRelevance::all($purchase_relevance_condition);
                $purchase_relevance_data = json_decode($purchase_relevance_data);
                if ($purchase_relevance_data) {
                    foreach ($purchase_relevance_data as $rel) {
                        if ($rel->order_sn_child) {
                            $order_relevance_condition = [];
                            $order_relevance_condition [] = ['order_sn_child', '=', $rel->order_sn_child];
                            $order_relevance_data = WaOrdersRelevance::find($order_relevance_condition);
                            $order_relevance_data = json_decode($order_relevance_data);
                            if ($order_relevance_data) {
                                $sales_count = intval($order_relevance_data->to_be_purchase_count) + intval($rel->count);
                                if ($sales_count > $order_relevance_data->count) {
                                    $sales_count = $order_relevance_data->count; // 不能大于最大的初始值
                                }
                                $order_relevance_up = [];
                                $order_relevance_up [] = ['order_sn_child', '=', $rel->order_sn_child];
                                $order_relevance_up_data = [
                                    'to_be_purchase_count' => $sales_count,
                                    'updated_at' => dateTime(),
                                ];
                                $order_relevance_up_result = WaOrdersRelevance::updated($order_relevance_up_data, $order_relevance_up);
                            }
                        }
                    }
                }

            } elseif ($param['purchase_orders_status'] == 8) {
                return IndexController::errored('', '有单独的删除接口');
            }
            $remark = '';
            $reason = '';
            $describe = '';
            // 采购合同操作日志
            //            self::purchaseOperateLog($param['purchase_order_sn'], $status, $adminId->id, $adminId->nickname,  $describe = '', $remark = '', $reason = '');
            $data = [
                'purchase_order_sn_parent' => $param['purchase_order_sn'],
                'status' => $param['purchase_orders_status'],
                'describe' => $describe,
                'remark' => $remark,
                'reason' => $reason,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];
            $ordersOperateLog = WaOrdersPurchaseOperateLog::created($data);
            if (!$ordersOperateLog) {
                return IndexController::errored('', '采购订单日志操作失败');
            }

            // 订单状态修改
//            $res = self::ordersStatusUp($param['purchase_order_sn'], $status);
            PublicCommentController::销售订单状态;
            $data = [
                'purchase_orders_status' => intval($param['purchase_orders_status']),
                'updated_at' => dateTime(),
            ];
            $where = [];
            $where [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $find = WaOrdersPurchase::find($where);
            $find = json_decode($find);
            if (!$find) {
                return IndexController::errored('', '查不到订单信息');
            }
            if (intval($find->purchase_orders_status) == $param['purchase_orders_status']) {
                echo '状态一致无需重复修改' . $find->purchase_orders_status;
                return IndexController::errored('', '状态一致无需重复修改');
            }
            $up = WaOrdersPurchase::updated($data, $where);
            if (!$up) {
                return IndexController::errored('', '采购订单状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('updatePurchaseOrderStatus', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 采购订单提交审批
     * @param Request $request
     */
    public function purchaseOrderSubmitApprove(Request $request)
    {
        //        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 根据采购单编号获取订单信息
        $orders = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取采购单信息失败');
        }

        $send_before = [];
        $send_after = [];

        if (array_key_exists('send_before',$param)){
            if ($param['send_before']){
                $send_before =  $param['send_before'];
            }
        }

        if (array_key_exists('send_after',$param)){
            if ($param['send_after']){
                $send_after =  $param['send_after'];
            }
        }

        // 获取当前用户对应部门所设置的审批流设置
//        $flow = ApproveSettingController::flowStting(2, $department_id);
        if (array_key_exists('flow', $param)) {
            $flow = $param['flow'];
//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息
            $admin_ids = json_encode($flow[0]['approve_admin_id']);

        } else {
            if (array_key_exists('sort', $param)) {
                if ($param['sort']) {
                    $sort = $param['sort'];
                } else {
                    $sort = 0;
                }
            } else {
                $sort = 0;
            }
            $flow = ApproveSettingController::flowSttingBySort(4, $sort);// sort默认选第一个
            $send_after = ApproveSettingController::flowSttingBySendBefore(4, $sort);// 抄送人 - 前 默认选第一个
            $send_before = ApproveSettingController::flowSttingBySendAfter(4, $sort);// 抄送人 - 前 默认选第一个
            $admin_ids = json_encode($flow[0]->approve_admin_id);
        }


        if (!$flow) {
            return IndexController::errored('ErrorApproveSetting', '当前用户所在部门未设置审批流程，无法提交审批');
        }


        \support\Db::beginTransaction();
        try {
            // 1审批中(提交审批):
            // 创建新的采购单审批 -> 创建采购单审批流第一条待审批记录
            // 判断 采购订单的状态 是否符合创建审批条件 是否同一笔审批未结束 采购单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
            $checkPurchaseApprove = WaPurchaseOrdersExamineApprove::find($adminId, ['purchase_order_sn' => $param['purchase_order_sn']]);
            $checkPurchaseApprove = json_decode($checkPurchaseApprove);
            if ($checkPurchaseApprove) {
                if ($checkPurchaseApprove->status == 0 || $checkPurchaseApprove->status == 1) {
                    return IndexController::errored('', '该订单在审批流程中不能重复创建');
                }
            }

            $po_no = 'PO' . IndexController::getRandomNum(6);
            $total_amount = 0;
            $total_amount = WaOrdersPurchaseRelevance::sums(['purchase_order_sn_parent' => $param['purchase_order_sn']]);
            $data = [
                'po_no' => $po_no, // 采购单编号
                'supplier_id' => $orders->supplier_id, // 供应商id
                'supplier_name' => $orders->supplier_name, // 供应商名称
                'total_amount' => $total_amount, // 订单金额
                'admin_id' => $adminId->id, // 创建人id(提交订单审批的创建人)
                'admin_name' => $adminId->nickname, // 创建人名称
                'initiator_admin_name' => $adminId->nickname, // 发起人
                'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
                'approve_flow' => json_encode($flow), // 当前采购订单的审批流流程
            ];
            if ($send_before) {
                $data['approve_flow_send_before'] = json_encode($send_before);
            }
            if ($send_after) {
                $data['approve_flow_send_after'] = json_encode($send_after);
            }
            if ($param['purchase_order_sn']) {
                $data['purchase_order_sn'] = $param['purchase_order_sn'];// 采购订单编号
            }

            $up_purchase_order = WaOrdersPurchase::updated(['po_no' => $po_no, 'updated_at' => dateTime()], ['purchase_order_sn' => $param['purchase_order_sn']]);
            if (!$up_purchase_order) {
                return IndexController::errored('', '采购订单对应审批订单编号更新失败');
            }
            $add_PurchaseEa = WaPurchaseOrdersExamineApprove::create($data); // 创建的审批id
            if (!$add_PurchaseEa) {
                return IndexController::errored('', '创建采购订单审批驳回');
            }
            // 创建审批流 1供应商审批 2销售订单审批 3销售合同审批 4采购订单审批 5采购合同审批 6采购请款审批 7交强险请款审批
//            // 采购订单审流 创建 (创建审批流中的第一个审批)
            $approve_log_data = [
                'po_no' => $po_no, // 采购订单编号
                'check_id' => $add_PurchaseEa, // 审批id
                'admin_ids' => $admin_ids, //
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'status' => 0, //待审批 1审批通过 2 审批驳回  4  删除
                'describe' => '待' . $admin_ids . '审核',

            ];

            if ($param['purchase_order_sn']) {
                $approve_log_data['purchase_order_sn'] = $param['purchase_order_sn'];// 采购订单编号
            }
            $res = WaPurchaseOrdersExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return IndexController::errored('', '创建采购订单审批流失败');
            }

            $remark = '';
            $reason = '';
            $describe = '';
            // 采购操作日志
            //            self::purchaseOperateLog($param['purchase_order_sn'], $status, $adminId->id, $adminId->nickname,  $describe = '', $remark = '', $reason = '');
            $data = [
                'purchase_order_sn_parent' => $param['purchase_order_sn'],
                'status' => 0,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => $reason,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];
            $ordersOperateLog = WaOrdersPurchaseOperateLog::created($data);
            if (!$ordersOperateLog) {
                return IndexController::errored('', '采购订单日志操作失败');
            }

            // 订单状态修改
//            $res = self::ordersStatusUp($param['purchase_order_sn'], $status);
            PublicCommentController::采购订单状态;
            $data = [
                'purchase_orders_status' => 1,
                'updated_at' => dateTime(),
            ];
            $where = [];
            $where [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $find = WaOrdersPurchase::find($where);
            $find = json_decode($find);
            if (!$find) {
                return IndexController::errored('', '查不到订单信息');
            }
//        if (intval($find->purchase_orders_status) == $param['purchase_orders_status']) {
//            echo '状态一致无需重复修改' . $find->purchase_orders_status;
//            return IndexController::errored('', '状态一致无需重复修改');
//        }
            $up = WaOrdersPurchase::updated($data, $where);
            if (!$up) {
                return IndexController::errored('', '采购订单状态更新失败');
            }
            $time = date('H:i:s', time());
            // 钉钉消息通知
            $admin_ids = json_decode($admin_ids);
            if ($admin_ids) {
                foreach ($admin_ids as $kadmin) {
                    $admin_condition = [];
                    $admin_condition [] = ['id', '=', $kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '采购订单审批', // 标题
                        'markdown' => '采购订单审批' . $time, // 内容
                    ];
                    $currentRoute = $request->host();

                    // 消息通知
                    if ($currentRoute == 'frontforeign.olivenev.com') {
                        $message = MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }

            \support\Db::commit();
            return IndexController::successed('', '提交审批成功');
        } catch (\Throwable $exception) {
            IndexController::logError('purchaseOrderSubmitApprove', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '采购订单提交审批失败');
        }

    }


    /**
     * 采购订单列表
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderList(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];
        $conditions = [];
        $between = [];
        $whereNotIn = [8];
        $whereStatusIn = [];
        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn', 'like', '%' . $param['purchase_order_sn'] . '%'];
        }


        if ($param['admin_name']) {
            $condition [] = ['admin_name', 'like', '%' . $param['admin_name'] . '%'];
        }

        //单状态查询
//        if ($param['purchase_orders_status'] || $param['purchase_orders_status'] == 0) {
//            $condition [] = ['purchase_orders_status', '=', $param['purchase_orders_status']]; // 采购单状态 0 草稿 1审批中 2待签署审批合同 3 进行中 4待供应商开票 5待配车 6已完成 7已作废 8删除
//        }

        // 多状态查询

        if ($param['purchase_orders_status']) {
            $whereStatusIn = $param['purchase_orders_status'];
        }
//        if ($param['start_time'] && $param['end_time']) {
//            $between [] = ['created_at', '>', $param['start_time']];
//            $between [] = ['created_at', '<', $param['end_time']];
//        }
        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        $whereIn = [];
        if (in_array($adminId->department_id, [44])) { // 采购部
            $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
            $whereIn = $next_epartment_members;
        }
        $pageNum = $param['pageNum'];
        $fields = ['*'];

        $page = $param['page'];
        $listOrder = WaOrdersPurchase::list($adminId, $page, $pageNum, $whereIn, $whereNotIn, $fields,$whereStatusIn, $condition, $between, $conditions);
        return IndexController::successed($listOrder, '采购订单列表');

    }

    /**
     * 采购订单列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];
        $whereNotIn = [7, 8];

        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn', 'like', '%' . $param['purchase_order_sn'] . '%'];
        }
        $listOrder = WaOrdersPurchase::all($condition, $whereNotIn);
        return IndexController::successed($listOrder, '采购订单列表-不分页');

    }

    /**
     * 采购订单子产品列表
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderAllChildren(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];

        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
        }

//        $listOrder = WaOrdersPurchase::allChildren($condition);
        $listOrder = WaOrdersPurchaseRelevance::allOrderBy($condition);

        return IndexController::successed($listOrder, '采购订单列表-不分页');

    }

    /**
     * 采购订单详情
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderDetail(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition_pur = ['purchase_order_sn' => $param['purchase_order_sn']];
        // 主订单信息
//        $order_pur_data = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
        $order_pur_data = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
        $order_pur_data = json_decode($order_pur_data);


        $condition = ['purchase_order_sn_parent' => $param['purchase_order_sn']];
        // 主订单信息
        $orderParentCondition = [];
        $orderParentCondition [] = ['purchase_order_sn','=',$param['purchase_order_sn']];
        $orderParentCondition [] = ['po_no','=',$order_pur_data->po_no];
        $orderParentData = WaOrdersPurchase::findApprove($adminId, $orderParentCondition,$order_pur_data);
        $orderParentData = json_decode($orderParentData);

        // 1 销售订单直接创建的采购单 2  间接（单独采购）创建的采购单
        if ($orderParentData) {
            if ($orderParentData->purchase_orders_type == 1) {
                $orderParentData->purchase_orders_type_name = '销售订单直接创建的采购单';
            } elseif ($orderParentData->purchase_orders_type == 2) {
                $orderParentData->purchase_orders_type_name = '间接（单独采购）创建的采购单';
            } else {
                $orderParentData->purchase_orders_type_name = '';
            }

            $orderParentData->supplier_type_name = IndexController::supplierTypeNameCommon($orderParentData->supplier_type);


        } else {
            return IndexController::errored('', '主订单信息获取失败');
        }

        $listOrder = [];// 当前订单的详情数据
        $quotationOrderChildren = WaOrdersPurchaseRelevance::all($condition);
        $quotationOrderChildren = json_decode($quotationOrderChildren);
        if ($quotationOrderChildren) {
            foreach ($quotationOrderChildren as $key) {
                $purchased_vehicles_data = WaPurchasedVehicles::all(['*'], ['model' => $key->model, 'purchase_children_sn' => $key->purchase_order_sn_child]);
                $key->purchased_vehicles_data = json_decode($purchased_vehicles_data);
                if ($key->registration_id) {
                    $registration = WaSupplier::find(['id' => $key->registration_id]);
                    $registration = json_decode($registration);
                    if ($registration) {
                        $key->registration_name = $registration->name;
                    } else {
                        $key->registration_name = '';
                    }
                } else {
                    $key->registration_name = '';
                }
                if ($key->transfer_export_id) {
                    $transfer_export = WaSupplier::find(['id' => $key->transfer_export_id]);
                    $transfer_export = json_decode($transfer_export);
                    if ($transfer_export) {
                        $key->transfer_export_name = $transfer_export->name;
                    } else {
                        $key->transfer_export_name = '';
                    }
                } else {
                    $key->transfer_export_name = '';
                }
                if ($key->price_options){
                    $key->price_options = json_decode($key->price_options);// 费用选项
                }
                if ($key->other_price){$key->other_price = json_decode($key->other_price);}
                if ($key->option_package){$key->option_package = json_decode($key->option_package);}


                // 是否新能源 1 是 2 传统能源
                if ($key->is_nev == 1) {
                    $key->is_nev_name = '新能源';
                } elseif ($key->is_nev == 2) {
                    $key->is_nev_name = '传统能源';
                } else {
                    $key->is_nev_name = '';
                }
            }
            $listOrder['purchaseOrderChildren'] = $quotationOrderChildren;  // 当前订单子订单详情列表
            $listOrder['orderParentData'] = $orderParentData; //  当前订单主订单的详情信息
            // $listOrder['contract_info'] = $contract_info; //  合同状态
            // 付款信息
            $confirm_payroll_requisition = WaPurchasePayrollRequisition::allByPur(['purchase_order_sn' => $param['purchase_order_sn']]);
            $confirm_payroll_requisition = json_decode($confirm_payroll_requisition);
            $listOrder['confirm_payroll_requisition'] = $confirm_payroll_requisition; //  付款信息


            // 采购定金
            $order_pur_data->deposit_price = round($order_pur_data->deposit_price, 2);
            if (!$order_pur_data->deposit_price) {
                // 定金为 0 无需请款
                $order_pur_data->deposit_price = 0;
                $listOrder['deposit_payroll_status'] = 0;
            }
            else {
                // 定金大于 0  需要请款
                //已请款定金金额
                $purchase_payroll_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 1], ['status', '<', 4]]);
                $purchase_payroll_find = json_decode($purchase_payroll_find);
                if ($purchase_payroll_find) {
                    //有请款
                    // 请款定金金额
                    $order_pur_data->deposit_price = round($order_pur_data->deposit_price, 2);
                    // 已付款定金
                    $deposit_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 1]]);
                    // 采购尾款
                    $balance_sums = round($order_pur_data->total_amount, 2) - $order_pur_data->deposit_price;
                    // 已支付尾款
                    $balance_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 2]]);
                   if ($deposit_sums > 0 && $deposit_sums < $order_pur_data->deposit_price) {
                        //未足额请款
                        $listOrder['deposit_payroll_status'] = 3;
                    } elseif ($deposit_sums >= $order_pur_data->deposit_price) {
                        //已足额请款
                        $listOrder['deposit_payroll_status'] = 2;
                    }else{
                        $purchase_payroll_wait_approve_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 1], ['status', '=', 1]]);
                        $purchase_payroll_wait_approve_find = json_decode($purchase_payroll_wait_approve_find);
                        if ($purchase_payroll_wait_approve_find){
                            //请款中
                            $listOrder['deposit_payroll_status'] = 1;
                        } else {
                            // 未请款
                            $listOrder['deposit_payroll_status'] = 4;
                        }
                    }
                } else {
                    // 未请款
                    $listOrder['deposit_payroll_status'] = 4;
                }
            }
            PublicCommentController::请款单状态;
            if ($listOrder['deposit_payroll_status'] == 0) {
//                $listOrder['deposit_payroll_status_name'] = '无定金';
                $orderParentData->deposit_payroll_status = 0;
                $orderParentData->deposit_payroll_status_name = '无定金';
            } elseif ($listOrder['deposit_payroll_status'] == 1) {
//                $listOrder['deposit_payroll_status_name'] = '定金未请款';
                $orderParentData->deposit_payroll_status = 1;
                $orderParentData->deposit_payroll_status_name = '定金请款中';
            } elseif ($listOrder['deposit_payroll_status'] == 2) {
//                $listOrder['deposit_payroll_status_name'] = '定金已足额请款';
                $orderParentData->deposit_payroll_status = 2;
                $orderParentData->deposit_payroll_status = '定金已足额请款';
            } elseif ($listOrder['deposit_payroll_status'] == 3) {
//                $listOrder['deposit_payroll_status_name'] = '定金未足额请款';
                $orderParentData->deposit_payroll_status = 3;
                $orderParentData->deposit_payroll_status_name = '定金未足额请款';

            } elseif ($listOrder['deposit_payroll_status'] == 4) {
//                $listOrder['deposit_payroll_status_name'] = '定金未请款';
                $orderParentData->deposit_payroll_status = 4;
                $orderParentData->deposit_payroll_status_name = '定金未请款';

            } else {
//                $listOrder['deposit_payroll_status_name'] = '暂无';
                $orderParentData->deposit_payroll_status = 999;
                $orderParentData->deposit_payroll_status_name = '暂无';
            }
            // 尾款肯定大于 0（这个无需在这里判断）  需要请款
            //已请款尾款金额
            $purchase_payroll_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 2], ['status', '<', 4]]);
            $purchase_payroll_find = json_decode($purchase_payroll_find);
            if ($purchase_payroll_find) {
                //有请款
                // 请款定金额
                $order_pur_data->deposit_price = round($order_pur_data->deposit_price, 2);
                // 已付款尾款
                $deposit_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 2]]);
                // 采购尾款
                $balance_price = round($order_pur_data->total_amount, 2) - $order_pur_data->deposit_price;
                // 已支付尾款
                $balance_sums = WaPurchasePayrollRequisition::sums([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 2]]);
                if ($balance_sums) {
                    if ($balance_sums >= $balance_price) {
                        //已足额请款
                        $listOrder['balance_payroll_status'] = 2;
                    }else{
                        //未足额请款
                        $listOrder['balance_payroll_status'] = 3;
                    }
                }else{

                    $purchase_payroll_wait_approve_find = WaPurchasePayrollRequisition::find([['purchase_order_sn', '=', $order_pur_data->purchase_order_sn], ['payroll_requisition_type', '=', 2], ['status', '=', 1]]);
                    $purchase_payroll_wait_approve_find = json_decode($purchase_payroll_wait_approve_find);
                    if ($purchase_payroll_wait_approve_find){
                        //请款中
                        $listOrder['balance_payroll_status'] = 1;
                    } else {
                        // 未请款
                        $listOrder['balance_payroll_status'] = 4;
                    }
                }
            } else {
                // 未请款
                $listOrder['balance_payroll_status'] = 4;
            }
            PublicCommentController::请款单状态;
            if ($listOrder['balance_payroll_status'] == 1) {
//                $listOrder['balance_payroll_status_name'] = '尾款未请款';
                $orderParentData->balance_payroll_status = 1;
                $orderParentData->balance_payroll_status_name = '尾款请款中';
            } elseif ($listOrder['balance_payroll_status'] == 2) {
//                $listOrder['balance_payroll_status_name'] = '尾款已足额请款';
                $orderParentData->balance_payroll_status = 2;
                $orderParentData->balance_payroll_status_name = '尾款已足额请款';
            } elseif ($listOrder['balance_payroll_status'] == 3) {
//                $listOrder['balance_payroll_status_name'] = '尾款已足额请款';
                $orderParentData->balance_payroll_status = 3;
                $orderParentData->balance_payroll_status_name = '尾款已足额请款';

            } elseif ($listOrder['balance_payroll_status'] == 4) {
//                $listOrder['balance_payroll_status_name'] = '尾款已足额请款';
                $orderParentData->balance_payroll_status = 4;
                $orderParentData->balance_payroll_status_name = '尾款未请款';

            } else {
//                $listOrder['balance_payroll_status_name'] = '暂无';
                $orderParentData->balance_payroll_status = 999;
                $orderParentData->balance_payroll_status_name = '暂无';
            }

            $confirm_vehicles = WaPurchasedVehicles::all('*', ['purchase_order_sn' => $param['purchase_order_sn']]);
            $confirm_vehicles = json_decode($confirm_vehicles);
            $listOrder['confirm_vehicles_info'] = $confirm_vehicles; //  配车信息

            // 开票信息
            $confirm_lnvoicing = WaOrdersPurchaseOperateLog::geted('*', ['purchase_order_sn_parent' => $param['purchase_order_sn'], 'status' => 5]);
            if ($confirm_lnvoicing) {
                $confirm_lnvoicing = json_decode($confirm_lnvoicing);
                $listOrder['confirm_lnvoicing_info'] = $confirm_lnvoicing; //  开票信息
            }

            // 配车信息
            $confirm_vehicles = WaPurchasedVehicles::all('*', ['purchase_order_sn' => $param['purchase_order_sn']]);
            $confirm_vehicles = json_decode($confirm_vehicles);
            $listOrder['confirm_vehicles_info'] = $confirm_vehicles; //  配车信息

//            //请款记录
//            $payroll_requisition_condition = [];
//            $payroll_requisition_condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
//            $payroll_requisition__info = WaPurchasePayrollRequisition::allByPur($payroll_requisition_condition);
//            if ($payroll_requisition__info){
//                $listOrder['payroll_requisition_info'] = json_decode($payroll_requisition__info); //  请款记录
//            }else{
//                $listOrder['payroll_requisition_info'] = [];
//            }


            $listOrder = json_encode($listOrder);

        }
        return IndexController::successed($listOrder, '采购订单列表');
    }

    /**
     * 关联采购订单列表
     * 选择状态为待签署采购合同 / 进行中的采购订单，且一个采购订单只允许被一份合同关联
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderByStatus(Request $request)
    {
//        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];
        if ($param['purchase_order_sn']) {
            $condition [] = ['purchase_order_sn', 'like', '%' . $param['purchase_order_sn'] . '%'];
        }
        //  新版：0 草稿 1 审批中 2 待签署采购合同 3 待支付定金 5待配车 6 已完成 7 已作废 9 审批失败
        if (intval($param['purchase_orders_status']) == 2 || intval($param['purchase_orders_status']) == 3 || intval($param['purchase_orders_status']) == 5 || intval($param['purchase_orders_status']) == 6) {
            $condition [] = ['purchase_orders_status', '=', $param['purchase_orders_status']];

            $res = WaOrdersPurchase::all($condition);
            return IndexController::successed($res, '关联采购订单列表');

        } else {
            return IndexController::errored('', '只有 待签署采购合同 / 进行中  / 待配车 可使用');

        }
    }

    /**
     * 采购合同-确认签署
     * @param Request $request
     * @return Response
     * 采购合同状态  0 草稿 1审批中 2待供应商签署 3已完成 4已作废 5 审核不通过 6 删除
     */
    public function purchaseContractConfirmSigning(Request $request)
    {
        // 订单状态 1审批中
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 获取合同信息
        $purchase_contract = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
        $purchase_contract = json_decode($purchase_contract);
        if (!$purchase_contract) {
            return IndexController::errored('', '获取合同信息失败');
        }
        $voucher = [
            'confirm_signing_model_one' => $param['confirm_signing_model_one'], // 确认签署 （上传合同附件*合同①:挂靠公司与供应商的采购合同）
            'confirm_signing_model_two' => $param['confirm_signing_model_two'], // 确认签署 （上传合同附件*合同②:挂靠公司与出口公司的采购合同）
        ];
        PublicCommentController::采购订单状态;
        $purchase_orders_status = 5;
        if ($param['confirm_signing_model_one']){
            $param['confirm_signing_model_one'] = json_encode($param['confirm_signing_model_one']);
        }
        if ($param['confirm_signing_model_two']){
            $param['confirm_signing_model_two'] = json_encode($param['confirm_signing_model_two']);
        }
        $data = [
            'confirm_signing_model_one' => $param['confirm_signing_model_one'], // 确认签署 （上传合同附件*合同①:挂靠公司与供应商的采购合同）
            'confirm_signing_model_two' => $param['confirm_signing_model_two'], // 确认签署 （上传合同附件*合同②:挂靠公司与出口公司的采购合同）
            'purchase_orders_status' => $purchase_orders_status,
            'updated_at' => dateTime(),
        ];

        $up_contract = WaOrdersPurchase::updated($data, ['purchase_order_sn' => $param['purchase_order_sn']]);
        if (!$up_contract) {
            return IndexController::errored('', '附件更新失败');
        }


        PublicCommentController::采购订单状态;// 采购订单状态
        $data = [
            'purchase_order_sn_parent' => $param['purchase_order_sn'], //
            'admin_id' => $adminId->id, // 创建人
            'admin_name' => $adminId->nickname, // 创建人名称
            'voucher' => json_encode($voucher), // 合同
            'created_at' => dateTime(),
            'status' => $purchase_orders_status, //
        ];


        \support\Db::beginTransaction();
        try {
            // 添加日志
            $add_log = WaOrdersPurchaseOperateLog::created($data);
            if (!$add_log) {
                return IndexController::errored('', '确认签署日志添加失败');
            }
            \support\Db::commit();
            return IndexController::successed($add_log, '确认签署合同成功');
        } catch (\Throwable $exception) {
            IndexController::logError('purchaseContractConfirmSigning', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '确认签署失败');
        }

    }

    public static function status($order_sn)
    {
        $find = WaOrdersPurchase::find(['purchase_order_sn' => $order_sn]);
        $find = json_decode($find);
        if (!$find) {
            return IndexController::errored('', '采购订单状态查询失败');
        }
        return json_encode($find->purchase_orders_status);
    }

    /**
     * 采购订单调用-销售订单列表-不分页  这个接口需要移动到销售订单那边去
     * @param Request $request
     * @return Response
     */
    public function salesOrderAllByPurchase(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $between = [];
        // 数据权限 1 默认全部  2 只看自己
//        if ($adminId->data_permission == 2) {
//            $condition [] = ['admin_id', '=', $adminId->id];
//        }
        if (array_key_exists('user_id', $param)) {
            if ($param['user_id']) {
                $condition [] = ['user_id', '=', $param['user_id'] ];
            }
        }
        if (array_key_exists('currency', $param)) {
            if ($param['currency']) {
                $condition [] = ['currency', '=', $param['currency'] ];
            }
        }

        if (array_key_exists('order_sn', $param)) {
            if ($param['order_sn']) {
                $condition [] = ['order_sn', 'like', '%' . $param['order_sn'] . '%'];
            }
        }
        if (array_key_exists('status', $param)) {
            if ($param['status']) {
                $condition [] = ['status', '=', $param['status']];
            } else {
                $condition [] = ['status', '=', 5]; // 采购中
            }
        }
        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
        $whereIn = $next_epartment_members;
        if (!$whereIn) {
            $whereIn = [];
        }


        $con_one = [];
        $con_two = [];
        $con_three = [];
        $con_four = [];
        if (array_key_exists('like_name', $param)) {
            if ($param['like_name']) {
                $con_one [] = ['brands_name', 'like', '%' . $param['like_name'] . '%'];
                $con_one [] = ['order_sn_parent', '=', ''];
//                $con_two [] = ['car_type', 'like', '%' . $param['like_name'] . '%'];
                $con_two [] = ['order_sn_parent', '=', ''];
                $con_three [] = ['series_name', 'like', '%' . $param['like_name'] . '%'];
                $con_three [] = ['order_sn_parent', '=', ''];
                $con_four [] = ['model', 'like', '%' . $param['like_name'] . '%'];
                $con_four [] = ['order_sn_parent', '=', ''];
                $listOrder = WaOrders::allByLike($condition, $con_one, $con_two, $con_three, $con_four);
            } else {
                $listOrder = WaOrders::alls($condition);
            }
        } else {
            $listOrder = WaOrders::alls($condition);
        }


        return IndexController::successed($listOrder, '销售订单不分页列表');

    }


    /**
     * ................................................下面的接口将废弃................................................
     */

    /**
     * 采购确认付款完成
     * @param Request $request
     * @return Response
     */
    public function purchaseConfirmPaymentCompletion(Request $request)
    {
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        $condition = [];
        $condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
        $bill_details = WaOrdersPurchaseAmountDetail::all($condition);

        if ($bill_details) {
            $bill_details = json_decode($bill_details);
            foreach ($bill_details as $ke) {
                if (round($ke->total_amount, 2) > 0) {
                    $where_payroll = [];
                    $where_payroll [] = ['purchase_order_sn', '=', $ke->purchase_order_sn];
                    $where_payroll [] = ['price_name', '=', $ke->price_name];
//                    $payroll_requisition = WaPurchasePayrollRequisition::allByPur($where_payroll);
//                    $payroll_requisition = json_decode($payroll_requisition);
                    // 总金额
                    $ke->total_amount = round($ke->total_amount, 2);
                    // 已请款
                    $ke->requested_price = WaPurchasePayrollRequisition::sums($where_payroll);

                    if ($ke->total_amount > $ke->requested_price) {
                        if (!in_array($ke->price_name, ['行情报价', '选装包总价格', '零售优惠']))
                            return IndexController::errored($ke->price_name, '还有请款未完成');
                    }
                }
            }
        }

        PublicCommentController::采购订单状态;// 采购订单状态
        $data = [
            'purchase_order_sn_parent' => $param['purchase_order_sn'], //
            'admin_id' => $adminId->id, // 创建人
            'admin_name' => $adminId->nickname, // 创建人名称
            'created_at' => dateTime(),
            'status' => 6,
        ];

        \support\Db::beginTransaction();
        try {
            // 添加日志
            $add_log = WaOrdersPurchaseOperateLog::created($data);
            if (!$add_log) {
                return IndexController::errored('', '修改失败');
            }
            // 更新入库状态
            $res = WaOrdersPurchase::updated(['purchase_orders_status' => 6, 'updated_at' => dateTime()], ['purchase_order_sn' => $param['purchase_order_sn']]);
            if (!$res) {
                return IndexController::errored('', '车辆确认开票状态更新失败');
            }

            \support\Db::commit();
            return IndexController::successed($res, '车辆确认开票成功');
        } catch (\Throwable $exception) {
            IndexController::logError('purchaseConfirmPaymentCompletion', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '车辆确认开票失败');
        }

        return IndexController::successed('', '请款已完成');


    }

    /**
     * 采购账单请款账类目明细
     * @param Request $request
     * @return Response
     */
    public function purchasePaymentDetail(Request $request)
    {

        //        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        $condition = [];
        $condition [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
        //  采购账单明细
        $bill_details = WaOrdersPurchaseAmountDetail::all($condition);
        $bill_details = json_decode($bill_details);

        if ($bill_details) {
            foreach ($bill_details as $ke) {
                if ($ke->purchase_order_sn) {
                    $where_payroll = [];
                    $where_payroll [] = ['purchase_order_sn', '=', $ke->purchase_order_sn];
                    $where_payroll [] = ['price_name', '=', $ke->price_name];
                    $payroll_requisition = WaPurchasePayrollRequisition::allByPur($where_payroll);
                    $payroll_requisition = json_decode($payroll_requisition);


                    $ke->requested_price = WaPurchasePayrollRequisition::sums($where_payroll);
                    if ($payroll_requisition) {
                        // 总金额
                        $ke->total_amount = round($ke->total_amount, 2);
                        // 已请款
                        $ke->requested_price = round(WaPurchasePayrollRequisition::sums($where_payroll), 2);
                        // 请款中
                        $ke->requested_pricing = round(WaPurchasePayrollRequisition::suming($where_payroll), 2);;
                        //  待请款
                        $ke->wait_price = $ke->total_amount - $ke->requested_price - $ke->requested_pricing;

                        $ke->payroll_requisition = $payroll_requisition;
                    } else {
                        $ke->payroll_requisition = [];
                    }
                } else {
                    $ke->payroll_requisition = [];
                }

            }
        }
        return IndexController::successed(json_encode($bill_details), '采购请款账单明细');

    }

    /**
     * 采购订单-确认开票
     * @param Request $request
     * @return Response
     */
    public function purchasedOrderConfirmLnvoicing(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if ($param['purchase_order_sn']) {
            $purchase_order = WaOrdersPurchase::find(['purchase_order_sn' => $param['purchase_order_sn']]);
            $purchase_order = json_decode($purchase_order);
            if (!$purchase_order) {
                return IndexController::errored('', '无法获取采购订单数据');
            }
        } else {
            return IndexController::errored('', '采购订单数据编号不能为空');
        }
        if ($param['end_time']) {
            $time = $param['end_time'];
        } else {
            $time = dateTime();
        }
        PublicCommentController::采购订单状态;// 采购订单状态
        $data = [
            'purchase_order_sn_parent' => $param['purchase_order_sn'], //
            'admin_id' => $adminId->id, // 创建人
            'admin_name' => $adminId->nickname, // 创建人名称
            'price' => round($param['price'], 2), // 开票金额
            'voucher' => json_encode($param['voucher']), // 发票 凭证
            'created_at' => $time,
            'remark' => $param['remark'],
            'status' => 6,
        ];
        if ($purchase_order->purchase_orders_status != 4) {
            return IndexController::errored('', '待供应商开票状态才能修改');
        }
        \support\Db::beginTransaction();
        try {
            // 添加日志
            $add_log = WaOrdersPurchaseOperateLog::created($data);
            if (!$add_log) {
                return IndexController::errored('', '车辆确认开票失败');
            }
            // 更新入库状态
            $res = WaOrdersPurchase::updated(['purchase_orders_status' => 5, 'updated_at' => dateTime()], ['purchase_order_sn' => $param['purchase_order_sn']]);
            if (!$res) {
                return IndexController::errored('', '车辆确认开票状态更新失败');
            }

            \support\Db::commit();
            return IndexController::successed($res, '车辆确认开票成功');
        } catch (\Throwable $exception) {
            IndexController::logError('purchasedOrderConfirmLnvoicing', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '车辆确认开票失败');
        }

    }

    /**
     * 更新-采购订单删除
     * @param Request $request
     * @return Response
     */
    public function purchaseOrderDelete(Request $request)
    {
//        process($request);
        // 获取参数信息
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = self::status($param['purchase_order_sn']);
        \support\Db::beginTransaction();
        try {
            // 采购订单状态 self::PurchaseOrdersStatus;
            if ($status != 0) {
                return IndexController::errored('', '草稿状态才能删除');
            }
            $remark = '';
            $reason = '';
            $describe = '';
            // 采购合同操作日志
            //            self::purchaseOperateLog($param['purchase_order_sn'], $status, $adminId->id, $adminId->nickname,  $describe = '', $remark = '', $reason = '');
            $data = [
                'purchase_order_sn_parent' => $param['purchase_order_sn'],
                'status' => 8,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => $reason,
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];
            $ordersOperateLog = WaOrdersPurchaseOperateLog::created($data);
            if (!$ordersOperateLog) {
                return IndexController::errored('', '采购订单日志操作失败');
            }
            //采购订单状态修改
            $data = [
                'purchase_orders_status' => 8, // 8 删除
                'updated_at' => dateTime(),
            ];
            $where = [];
            $where [] = ['purchase_order_sn', '=', $param['purchase_order_sn']];
            $find = WaOrdersPurchase::find($where);
            $find = json_decode($find);
            if (!$find) {
                return IndexController::errored('', '查不到订单信息');
            }
            $up = WaOrdersPurchase::updated($data, $where);
            if (!$up) {
                return IndexController::errored('', '采购订单删除失败');
            }


            // 销售订单代采购数量 返还
            $purchase_relevance_condition = [];
            $purchase_relevance_condition [] = ['purchase_order_sn_parent', '=', $param['purchase_order_sn']];
            $purchase_relevance_data = WaOrdersPurchaseRelevance::all($purchase_relevance_condition);
            $purchase_relevance_data = json_decode($purchase_relevance_data);
            if ($purchase_relevance_data) {
                foreach ($purchase_relevance_data as $rel) {
                    //采购订单(可以是多个订单多个车型)中某个车型已采购数量
                    $where_purchase_count = [];
                    $where_purchase_count [] = ['purchase_order_sn_child', '=', $rel->purchase_order_sn_child];
                    $where_purchase_count [] = ['status', '!=', 7];

                    $sums_purchase_count = WaOrdersPurchaseRelevance::countPur($where_purchase_count);

                    if ($rel->order_sn_child) {
                        $order_relevance_condition = [];
                        $order_relevance_condition [] = ['order_sn_child', '=', $rel->order_sn_child];
                        $order_relevance_data = WaOrdersRelevance::find($order_relevance_condition);
                        $order_relevance_data = json_decode($order_relevance_data);
                        if ($order_relevance_data) {
                            $sales_count = intval($order_relevance_data->to_be_purchase_count) + intval($sums_purchase_count);
                            $order_relevance_up = [];
                            $order_relevance_up [] = ['order_sn_child', '=', $rel->order_sn_child];
                            $order_relevance_up_data = [
                                'to_be_purchase_count' => $sales_count,
                                'updated_at' => dateTime(),
                            ];
                            $order_relevance_up_result = WaOrdersRelevance::updated($order_relevance_up_data, $order_relevance_up);

                        }
                    }
                }
            }

            \support\Db::commit();
            return IndexController::successed('', '已删除');
        } catch (\Throwable $exception) {
            IndexController::logError('purchaseOrderDelete', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '删除失败');
        }
    }

    public static function returnSalesRelevanceCount($purchase_order_sn)
    {
        // 销售订单代采购数量 返还
        $purchase_relevance_condition = [];
        $purchase_relevance_condition [] = ['order_sn_parent', '=', $purchase_order_sn];
        $purchase_relevance_data = WaOrdersPurchaseRelevance::all($purchase_relevance_condition);
        $purchase_relevance_data = json_decode($purchase_relevance_data);
        if ($purchase_relevance_data) {
            foreach ($purchase_relevance_data as $rel) {
                if ($rel->order_sn_child) {
                    $order_relevance_condition = [];
                    $order_relevance_condition [] = ['order_sn_child', '=', $rel->order_sn_child];
                    $order_relevance_data = WaOrdersRelevance::find($order_relevance_condition);
                    $order_relevance_data = json_decode($order_relevance_data);
                    if ($order_relevance_data) {
                        $sales_count = intval($order_relevance_data->to_be_purchase_count) + intval($order_relevance_data->count);
                        $order_relevance_up = [];
                        $order_relevance_up [] = ['order_sn_child', '=', $rel->order_sn_child];
                        $order_relevance_up_data = [
                            'to_be_purchase_count' => $sales_count,
                            'updated_at' => dateTime(),
                        ];
                        $order_relevance_up_result = WaOrdersRelevance::updated($order_relevance_up_data, $order_relevance_up);

                    }
                }
            }
        }

        return true;
    }


}